TL ; DR:
C++ has three access specifiers:
public:,private:, andprotected:. They appear as labels in the class body and apply to everything below them until the next label.By default, members of a
classareprivate(and members of astructarepublic):class Dog { private: string name; // hidden from outside public: Dog(string name) { this->name = name; } string getName() { return name; } };
Outside the class,
rex.nameis a compile error. Userex.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: RexFree plan: 30 tutor messages. PRO is unlimited.
