Public, Protected, and Private

beginner c++11 classes

C++ has three levels of access modifiers for classes: public, protected, and private. public means any code can access the field or method, while private means only the class itself can access those fields. protected is in between, code outside the class cannot access protected fields but the class itself and subclasses can access protected fields. By default, class members are private, and struct members are public. Here’s an example:

#include <string>
#include <iostream>

class Person {
public:
  explicit Person(int age) : age(age) {
  }

  void happy_birthday() {
    age += 1;
    std::cout << "It's " << nickname << "'s birthday.\n";
    std::cout << "You're " << age << ". Have anything to say?\n";
    std::cout << "\"" << catchphrase << "\"\n";
  }

  std::string nickname;

protected:
  std::string catchphrase = "Once more around the Sun.";

private:
  int age = 25;
};

class HappyPerson : public Person {
public:
  explicit HappyPerson(int age) : Person(age) {
    catchphrase = "I'm just glad to be here.";
  }
};

int main() {
  Person p(25);
  p.nickname = "Johnny";
  p.happy_birthday();

  std::cout << "\n";

  HappyPerson hp(20);
  hp.nickname = "Happy Gal";
  hp.happy_birthday();
}
It's Johnny's birthday.
You're 26. Have anything to say?
"Once more around the Sun."

It's Happy Gal's birthday.
You're 21. Have anything to say?
"I'm just glad to be here."

For more C++ By Example, click here.