[c++] What is the difference between private and protected members of C++ classes?

What is the difference between private and protected members in C++ classes?

I understand from best practice conventions that variables and functions which are not called outside the class should be made private—but looking at my MFC project, MFC seems to favor protected.

What's the difference and which should I use?

This question is related to c++ class oop private protected

The answer is


private is preferred for member data. Members in C++ classes are private by default.

public is preferred for member functions, though it is a matter of opinion. At least some methods must be accessible. public is accessible to all. It is the most flexible option and least safe. Anybody can use them, and anybody can misuse them.

private is not accessible at all. Nobody can use them outside the class, and nobody can misuse them. Not even in derived classes.

protected is a compromise because it can be used in derived classes. When you derive from a class, you have a good understanding of the base class, and you are careful not to misuse these members.

MFC is a C++ wrapper for Windows API, it prefers public and protected. Classes generated by Visual Studio wizard have an ugly mix of protected, public, and private members. But there is some logic to MFC classes themselves.

Members such as SetWindowText are public because you often need to access these members.

Members such as OnLButtonDown, handle notifications received by the window. They should not be accessed, therefore they are protected. You can still access them in the derived class to override these functions.

Some members have to do threads and message loops, they should not be accessed or override, so they are declared as private

In C++ structures, members are public by default. Structures are usually used for data only, not methods, therefore public declaration is considered safe.


Protected members can be accessed from derived classes. Private ones can't.

class Base {

private: 
  int MyPrivateInt;
protected: 
  int MyProtectedInt;
public:
  int MyPublicInt;
};

class Derived : Base
{
public:
  int foo1()  { return MyPrivateInt;} // Won't compile!
  int foo2()  { return MyProtectedInt;} // OK  
  int foo3()  { return MyPublicInt;} // OK
};??

class Unrelated 
{
private:
  Base B;
public:
  int foo1()  { return B.MyPrivateInt;} // Won't compile!
  int foo2()  { return B.MyProtectedInt;} // Won't compile
  int foo3()  { return B.MyPublicInt;} // OK
};

In terms of "best practice", it depends. If there's even a faint possibility that someone might want to derive a new class from your existing one and need access to internal members, make them Protected, not Private. If they're private, your class may become difficult to inherit from easily.


  • Private: It is an access specifier. By default the instance (member) variables or the methods of a class in c++/java are private. During inheritance, the code and the data are always inherited but is not accessible outside the class. We can declare our data members as private so that no one can make direct changes to our member variables and we can provide public getters and setters in order to change our private members. And this concept is always applied in the business rule.

  • Protected: It is also an access specifier. In C++, the protected members are accessible within the class and to the inherited class but not outside the class. In Java, the protected members are accessible within the class, to the inherited class as well as to all the classes within the same package.


A protected nonstatic base class member can be accessed by members and friends of any classes derived from that base class by using one of the following:

  • A pointer to a directly or indirectly derived class
  • A reference to a directly or indirectly derived class
  • An object of a directly or indirectly derived class

private and protected access modifiers are one and same only that protected members of the base class can be accessed outside the scope of the base class in the child(derived)class. It also applies the same to inheritance . But with the private modifier the members of the base class can only be accessed in the scope or code of the base class and its friend functions only''''


Attributes and methods marked as protected are -- unlike private ones -- still visible in subclasses.

Unless you don't want to use or provide the possibility to override the method in possible subclasses, I'd make them private.


Protected members can be accessed from derived classes. Private ones can't.

class Base {

private: 
  int MyPrivateInt;
protected: 
  int MyProtectedInt;
public:
  int MyPublicInt;
};

class Derived : Base
{
public:
  int foo1()  { return MyPrivateInt;} // Won't compile!
  int foo2()  { return MyProtectedInt;} // OK  
  int foo3()  { return MyPublicInt;} // OK
};??

class Unrelated 
{
private:
  Base B;
public:
  int foo1()  { return B.MyPrivateInt;} // Won't compile!
  int foo2()  { return B.MyProtectedInt;} // Won't compile
  int foo3()  { return B.MyPublicInt;} // OK
};

In terms of "best practice", it depends. If there's even a faint possibility that someone might want to derive a new class from your existing one and need access to internal members, make them Protected, not Private. If they're private, your class may become difficult to inherit from easily.


Attributes and methods marked as protected are -- unlike private ones -- still visible in subclasses.

Unless you don't want to use or provide the possibility to override the method in possible subclasses, I'd make them private.


Sure take a look at the Protected Member Variables question. It is recommended to use private as a default (just like C++ classses do) to reduce coupling. Protected member variables are most always a bad idea, protected member functions can be used for e.g. the Template Method pattern.


Since no public member function is needed to fetch and update protected members in the derived class, this increases the efficiency of code and reduces the amount of code we need to write. However, programmer of the derived class is supposed to be aware of what he is doing.


It all depends on what you want to do, and what you want the derived classes to be able to see.

class A
{
private:
    int _privInt = 0;
    int privFunc(){return 0;}
    virtual int privVirtFunc(){return 0;}
protected:
    int _protInt = 0;
    int protFunc(){return 0;}
public:
    int _publInt = 0;
    int publFunc()
    {
         return privVirtFunc();
    }
};

class B : public A
{
private:
    virtual int privVirtFunc(){return 1;}
public:
    void func()
    {
        _privInt = 1; // wont work
        _protInt = 1; // will work
        _publInt = 1; // will work
        privFunc(); // wont work
        privVirtFunc(); // wont work
        protFunc(); // will work
        publFunc(); // will return 1 since it's overridden in this class
    }
}

Attributes and methods marked as protected are -- unlike private ones -- still visible in subclasses.

Unless you don't want to use or provide the possibility to override the method in possible subclasses, I'd make them private.


The reason that MFC favors protected, is because it is a framework. You probably want to subclass the MFC classes and in that case a protected interface is needed to access methods that are not visible to general use of the class.


Private : Accessible by class member functions & friend function or friend class. For C++ class this is default access specifier.

Protected: Accessible by class member functions, friend function or friend class & derived classes.

  • You can keep class member variable or function (even typedefs or inner classes) as private or protected as per your requirement.
  • Most of the time you keep class member as a private and add get/set functions to encapsulate. This helps in maintenance of code.
  • Generally private function is used when you want to keep your public functions modular or to eliminate repeated code instead of writing whole code in to single function. This helps in maintenance of code.

Refer this link for more detail.


Sure take a look at the Protected Member Variables question. It is recommended to use private as a default (just like C++ classses do) to reduce coupling. Protected member variables are most always a bad idea, protected member functions can be used for e.g. the Template Method pattern.


private = accessible by the mothership (base class) only (ie only my parent can go into my parent's bedroom)

protected = accessible by mothership (base class), and her daughters (ie only my parent can go into my parent's bedroom, but gave son/daughter permission to walk into parent's bedroom)

public = accessible by mothership (base class), daughter, and everyone else (ie only my parent can go into my parent's bedroom, but it's a house party - mi casa su casa)


Public members of a class A are accessible for all and everyone.

Protected members of a class A are not accessible outside of A's code, but is accessible from the code of any class derived from A.

Private members of a class A are not accessible outside of A's code, or from the code of any class derived from A.

So, in the end, choosing between protected or private is answering the following questions: How much trust are you willing to put into the programmer of the derived class?

By default, assume the derived class is not to be trusted, and make your members private. If you have a very good reason to give free access of the mother class' internals to its derived classes, then you can make them protected.


Private member can be accessed only in same class where it has declared where as protected member can be accessed in class where it is declared along with the classes which are inherited by it .


  • Private: It is an access specifier. By default the instance (member) variables or the methods of a class in c++/java are private. During inheritance, the code and the data are always inherited but is not accessible outside the class. We can declare our data members as private so that no one can make direct changes to our member variables and we can provide public getters and setters in order to change our private members. And this concept is always applied in the business rule.

  • Protected: It is also an access specifier. In C++, the protected members are accessible within the class and to the inherited class but not outside the class. In Java, the protected members are accessible within the class, to the inherited class as well as to all the classes within the same package.


Public members of a class A are accessible for all and everyone.

Protected members of a class A are not accessible outside of A's code, but is accessible from the code of any class derived from A.

Private members of a class A are not accessible outside of A's code, or from the code of any class derived from A.

So, in the end, choosing between protected or private is answering the following questions: How much trust are you willing to put into the programmer of the derived class?

By default, assume the derived class is not to be trusted, and make your members private. If you have a very good reason to give free access of the mother class' internals to its derived classes, then you can make them protected.


The reason that MFC favors protected, is because it is a framework. You probably want to subclass the MFC classes and in that case a protected interface is needed to access methods that are not visible to general use of the class.


private members are only accessible from within the class, protected members are accessible in the class and derived classes. It's a feature of inheritance in OO languages.

You can have private, protected and public inheritance in C++, which will determine what derived classes can access in the inheritance hierarchy. C# for example only has public inheritance.


A protected nonstatic base class member can be accessed by members and friends of any classes derived from that base class by using one of the following:

  • A pointer to a directly or indirectly derived class
  • A reference to a directly or indirectly derived class
  • An object of a directly or indirectly derived class

Protected members can be accessed from derived classes. Private ones can't.

class Base {

private: 
  int MyPrivateInt;
protected: 
  int MyProtectedInt;
public:
  int MyPublicInt;
};

class Derived : Base
{
public:
  int foo1()  { return MyPrivateInt;} // Won't compile!
  int foo2()  { return MyProtectedInt;} // OK  
  int foo3()  { return MyPublicInt;} // OK
};??

class Unrelated 
{
private:
  Base B;
public:
  int foo1()  { return B.MyPrivateInt;} // Won't compile!
  int foo2()  { return B.MyProtectedInt;} // Won't compile
  int foo3()  { return B.MyPublicInt;} // OK
};

In terms of "best practice", it depends. If there's even a faint possibility that someone might want to derive a new class from your existing one and need access to internal members, make them Protected, not Private. If they're private, your class may become difficult to inherit from easily.


private and protected access modifiers are one and same only that protected members of the base class can be accessed outside the scope of the base class in the child(derived)class. It also applies the same to inheritance . But with the private modifier the members of the base class can only be accessed in the scope or code of the base class and its friend functions only''''


Protected members can only be accessed by descendants of the class, and by code in the same module. Private members can only be accessed by the class they're declared in, and by code in the same module.

Of course friend functions throw this out the window, but oh well.


It all depends on what you want to do, and what you want the derived classes to be able to see.

class A
{
private:
    int _privInt = 0;
    int privFunc(){return 0;}
    virtual int privVirtFunc(){return 0;}
protected:
    int _protInt = 0;
    int protFunc(){return 0;}
public:
    int _publInt = 0;
    int publFunc()
    {
         return privVirtFunc();
    }
};

class B : public A
{
private:
    virtual int privVirtFunc(){return 1;}
public:
    void func()
    {
        _privInt = 1; // wont work
        _protInt = 1; // will work
        _publInt = 1; // will work
        privFunc(); // wont work
        privVirtFunc(); // wont work
        protFunc(); // will work
        publFunc(); // will return 1 since it's overridden in this class
    }
}

Private member can be accessed only in same class where it has declared where as protected member can be accessed in class where it is declared along with the classes which are inherited by it .


Public members of a class A are accessible for all and everyone.

Protected members of a class A are not accessible outside of A's code, but is accessible from the code of any class derived from A.

Private members of a class A are not accessible outside of A's code, or from the code of any class derived from A.

So, in the end, choosing between protected or private is answering the following questions: How much trust are you willing to put into the programmer of the derived class?

By default, assume the derived class is not to be trusted, and make your members private. If you have a very good reason to give free access of the mother class' internals to its derived classes, then you can make them protected.


It all depends on what you want to do, and what you want the derived classes to be able to see.

class A
{
private:
    int _privInt = 0;
    int privFunc(){return 0;}
    virtual int privVirtFunc(){return 0;}
protected:
    int _protInt = 0;
    int protFunc(){return 0;}
public:
    int _publInt = 0;
    int publFunc()
    {
         return privVirtFunc();
    }
};

class B : public A
{
private:
    virtual int privVirtFunc(){return 1;}
public:
    void func()
    {
        _privInt = 1; // wont work
        _protInt = 1; // will work
        _publInt = 1; // will work
        privFunc(); // wont work
        privVirtFunc(); // wont work
        protFunc(); // will work
        publFunc(); // will return 1 since it's overridden in this class
    }
}

Protected members can be accessed from derived classes. Private ones can't.

class Base {

private: 
  int MyPrivateInt;
protected: 
  int MyProtectedInt;
public:
  int MyPublicInt;
};

class Derived : Base
{
public:
  int foo1()  { return MyPrivateInt;} // Won't compile!
  int foo2()  { return MyProtectedInt;} // OK  
  int foo3()  { return MyPublicInt;} // OK
};??

class Unrelated 
{
private:
  Base B;
public:
  int foo1()  { return B.MyPrivateInt;} // Won't compile!
  int foo2()  { return B.MyProtectedInt;} // Won't compile
  int foo3()  { return B.MyPublicInt;} // OK
};

In terms of "best practice", it depends. If there's even a faint possibility that someone might want to derive a new class from your existing one and need access to internal members, make them Protected, not Private. If they're private, your class may become difficult to inherit from easily.


Protected members can only be accessed by descendants of the class, and by code in the same module. Private members can only be accessed by the class they're declared in, and by code in the same module.

Of course friend functions throw this out the window, but oh well.


It all depends on what you want to do, and what you want the derived classes to be able to see.

class A
{
private:
    int _privInt = 0;
    int privFunc(){return 0;}
    virtual int privVirtFunc(){return 0;}
protected:
    int _protInt = 0;
    int protFunc(){return 0;}
public:
    int _publInt = 0;
    int publFunc()
    {
         return privVirtFunc();
    }
};

class B : public A
{
private:
    virtual int privVirtFunc(){return 1;}
public:
    void func()
    {
        _privInt = 1; // wont work
        _protInt = 1; // will work
        _publInt = 1; // will work
        privFunc(); // wont work
        privVirtFunc(); // wont work
        protFunc(); // will work
        publFunc(); // will return 1 since it's overridden in this class
    }
}

Private : Accessible by class member functions & friend function or friend class. For C++ class this is default access specifier.

Protected: Accessible by class member functions, friend function or friend class & derived classes.

  • You can keep class member variable or function (even typedefs or inner classes) as private or protected as per your requirement.
  • Most of the time you keep class member as a private and add get/set functions to encapsulate. This helps in maintenance of code.
  • Generally private function is used when you want to keep your public functions modular or to eliminate repeated code instead of writing whole code in to single function. This helps in maintenance of code.

Refer this link for more detail.


Since no public member function is needed to fetch and update protected members in the derived class, this increases the efficiency of code and reduces the amount of code we need to write. However, programmer of the derived class is supposed to be aware of what he is doing.


Protected members can only be accessed by descendants of the class, and by code in the same module. Private members can only be accessed by the class they're declared in, and by code in the same module.

Of course friend functions throw this out the window, but oh well.


private = accessible by the mothership (base class) only (ie only my parent can go into my parent's bedroom)

protected = accessible by mothership (base class), and her daughters (ie only my parent can go into my parent's bedroom, but gave son/daughter permission to walk into parent's bedroom)

public = accessible by mothership (base class), daughter, and everyone else (ie only my parent can go into my parent's bedroom, but it's a house party - mi casa su casa)


Public members of a class A are accessible for all and everyone.

Protected members of a class A are not accessible outside of A's code, but is accessible from the code of any class derived from A.

Private members of a class A are not accessible outside of A's code, or from the code of any class derived from A.

So, in the end, choosing between protected or private is answering the following questions: How much trust are you willing to put into the programmer of the derived class?

By default, assume the derived class is not to be trusted, and make your members private. If you have a very good reason to give free access of the mother class' internals to its derived classes, then you can make them protected.


Sure take a look at the Protected Member Variables question. It is recommended to use private as a default (just like C++ classses do) to reduce coupling. Protected member variables are most always a bad idea, protected member functions can be used for e.g. the Template Method pattern.


Attributes and methods marked as protected are -- unlike private ones -- still visible in subclasses.

Unless you don't want to use or provide the possibility to override the method in possible subclasses, I'd make them private.


Protected members can only be accessed by descendants of the class, and by code in the same module. Private members can only be accessed by the class they're declared in, and by code in the same module.

Of course friend functions throw this out the window, but oh well.


The reason that MFC favors protected, is because it is a framework. You probably want to subclass the MFC classes and in that case a protected interface is needed to access methods that are not visible to general use of the class.


Sure take a look at the Protected Member Variables question. It is recommended to use private as a default (just like C++ classses do) to reduce coupling. Protected member variables are most always a bad idea, protected member functions can be used for e.g. the Template Method pattern.


private is preferred for member data. Members in C++ classes are private by default.

public is preferred for member functions, though it is a matter of opinion. At least some methods must be accessible. public is accessible to all. It is the most flexible option and least safe. Anybody can use them, and anybody can misuse them.

private is not accessible at all. Nobody can use them outside the class, and nobody can misuse them. Not even in derived classes.

protected is a compromise because it can be used in derived classes. When you derive from a class, you have a good understanding of the base class, and you are careful not to misuse these members.

MFC is a C++ wrapper for Windows API, it prefers public and protected. Classes generated by Visual Studio wizard have an ugly mix of protected, public, and private members. But there is some logic to MFC classes themselves.

Members such as SetWindowText are public because you often need to access these members.

Members such as OnLButtonDown, handle notifications received by the window. They should not be accessed, therefore they are protected. You can still access them in the derived class to override these functions.

Some members have to do threads and message loops, they should not be accessed or override, so they are declared as private

In C++ structures, members are public by default. Structures are usually used for data only, not methods, therefore public declaration is considered safe.


The reason that MFC favors protected, is because it is a framework. You probably want to subclass the MFC classes and in that case a protected interface is needed to access methods that are not visible to general use of the class.


private members are only accessible from within the class, protected members are accessible in the class and derived classes. It's a feature of inheritance in OO languages.

You can have private, protected and public inheritance in C++, which will determine what derived classes can access in the inheritance hierarchy. C# for example only has public inheritance.


Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to class

String method cannot be found in a main class method Class constructor type in typescript? ReactJS - Call One Component Method From Another Component How do I declare a model class in my Angular 2 component using TypeScript? When to use Interface and Model in TypeScript / Angular Swift Error: Editor placeholder in source file Declaring static constants in ES6 classes? Creating a static class with no instances In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric Static vs class functions/variables in Swift classes?

Examples related to oop

How to implement a simple scenario the OO way When to use 'raise NotImplementedError'? PHP: cannot declare class because the name is already in use Python class input argument Call an overridden method from super class in typescript Typescript: How to extend two classes? What's the difference between abstraction and encapsulation? An object reference is required to access a non-static member Java Multiple Inheritance Why not inherit from List<T>?

Examples related to private

Private class declaration Python read-only property What is the use of a private static variable in Java? How to access private data members outside the class without making "friend"s? JUnit Testing private variables? What are access specifiers? Should I inherit with private, protected or public? Do subclasses inherit private fields? What is the difference between public, private, and protected? Internal vs. Private Access Modifiers Private Variables and Methods in Python

Examples related to protected

What are access specifiers? Should I inherit with private, protected or public? What is the difference between public, private, and protected? What is the difference between private and protected members of C++ classes? What is the difference between public, protected, package-private and private in Java?