C++ Tutorial · Object-Oriented C++ · Lesson 12 of 21
C++ Classes and Objects
Classes, access specifiers, constructors, member functions and const.
Classes
A class groups data members and member functions. public members form the interface; private members hide implementation:
#include <iostream>
#include <string>
class BankAccount {
public:
explicit BankAccount(std::string owner) : owner_(std::move(owner)) {}
void deposit(double amount) {
if (amount > 0) balance_ += amount;
}
bool withdraw(double amount) {
if (amount > balance_) return false;
balance_ -= amount;
return true;
}
const std::string& owner() const { return owner_; }
double balance() const { return balance_; }
private:
std::string owner_;
double balance_ = 0;
};
int main() {
BankAccount acct("Ada");
acct.deposit(100);
std::cout << std::boolalpha << acct.withdraw(30) << ' ' << acct.withdraw(500) << '\n';
std::cout << acct.owner() << ": " << acct.balance() << '\n';
}
Output
true false Ada: 70
Run this on your computer — see “Get Started” for setup.
- The member initialiser list (
: owner_(owner)) initialises members efficiently. constmember functions promise not to modify the object.explicitconstructors prevent accidental implicit conversions.
Test yourself
What does const after a member function's parameter list mean?
It returns a constantThe function doesn't modify the objectIt can only be called onceIt's a static function
Show answer
Answer: The function doesn't modify the object