c++ private and protected member inheritance

100 Views Asked by At
#include <iostream>
using namespace std;

// Base class
class Base {
private:
    int a = 10;

public:
    void get () {
        cout << "Get:" << a << endl;
    }
};

// Derived class
class Child : public Base {
};

int main() {
    Child Childobj;
    Childobj.get();

    return 0;   
}

I know that the private members of the Base class can't be inherited but I have accessed the private member int a; with the help of the public get() method.

My question is that: Does the private member of the Base class is sharing memory for the child object or child object just has the permission to access from the Base class?
In the case of public and protected, Do the protected and public members of the Base class share memories for the child object?

My confusion: My confusion is that I am unsure when accessing the private and protected members from the Base class, if the data members are being accessed and displayed from the object' memory so that I know the current state of the child object when Child class object is created? Thanks a lot!

1

There are 1 best solutions below

0
user12002570 On

I know that the private members of the Base class can't be inherited

This isn't true. All members of the base(whether private-protected-public) are inherited by the derived. Access specifier only affect the accessibility of the members i.e., they specify who has direct access to them.


Does the private member of the Base class is sharing memory for the child object or child object just has the permission to access from the Base class?

It isn't clear what you mean by "sharing memory" here. The member function get is public which means that users of the class has direct access to get. Moreover get is also inherited by the derived class. So when you wrote Childobj.get() name lookup finds the inherited member get and uses it.