0

My questions is why b.getmultiply(); will not cause compilation error?

Class B is private inherit from class A, and x and y are members of class A.

class A {
    public:
    int x;
    int y;
    void set(int a, int b) { x = a; y =b;}
    };

class B : private A{
    public:
    int getmultiply (void){
        return x*y;}
};  

int main(void)
{
   B b;
    //b.set(3,4);     // this will cause compilation error
   cout << b.getmultiply();   // why this will not?? 
   return 0;
}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
jmmom
  • 313
  • 3
  • 7

2 Answers2

3

When you private inherit from a base class, its public members become private members of the derived class. These members are public and accessible inside of member functions of the derived class (e.g. B.getmultiply()), but are private and not accessible to outside code (e.g. main()) that is not a friend of the derived class.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
0

When a class privately inherits from another, it still has access to that class's (non-private) members just like under public inheritance. It is only the outside world that doesn't have this access to them because they become private in the context of the derived class (in fact the outside world doesn't even know the derived is a derived: you can't refer to an instance of B with a pointer of type A for example).

Smeeheey
  • 9,906
  • 23
  • 39