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:

Example 1
#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.
  • const member functions promise not to modify the object.
  • explicit constructors prevent accidental implicit conversions.

Test yourself

What does const after a member function's parameter list mean?

  1. It returns a constant
  2. The function doesn't modify the object
  3. It can only be called once
  4. It's a static function
Show answer

Answer: The function doesn't modify the object