Start learning free

LESSON 624 OF 667 · OBJECT-ORIENTED PROGRAMMING

Access Specifiers in C++

Lesson

TL ; DR:

  • C++ has three access specifiers: public:, private:, and protected:. They appear as labels in the class body and apply to everything below them until the next label.


  • By default, members of a class are private (and members of a struct are public):

    class Dog {
    private:
        string name;          // hidden from outside
    public:
        Dog(string name) { this->name = name; }
        string getName() { return name; }
    };
    

  • Outside the class, rex.name is a compile error. Use rex.getName() instead.



Full lesson:

Access specifiers in C++ work like access modifiers in Java/C#, but with different syntax — they're section labels rather than per-member modifiers.


class BankAccount {
private:
    double balance;        // hidden

public:
    void deposit(double amount) {
        if (amount < 0) return;
        balance += amount;
    }
    double getBalance() { return balance; }
};

If balance were public, any client could just write account.balance = -1000; and corrupt the state.


Your task

The Dog class has its name member in a private: block. Add a string getName() member function under public: that returns name.

Dog's name: Rex
STEP 1 OF 2
    Ctrl + Enter to check