0

I was learning about inheritance. If we have used private access specifier in base class then it is not accessible in derived class. But I have a doubt regarding this.

#include<bits/stdc++.h>
using namespace std;

class A
{
    private:
    int a;
    int b;
    int c;
    public:
        int d;
        void print()
        {
            cout<<"Inside A Print()"<<endl;
        }
        
};
class B: public A
{
    private:
        int a1,b1,c1;
    public:
            B()
            {
            
            }
            void print()
            {
                cout<<"Inside B Print()"<<endl;
            }       
};
int main()
{
    B obj;
    cout<<sizeof(obj)<<endl;
    return 0;
}

Since I have used public access specifier during inheriting class A. Since we know that private member of base class is not accessible at all. So output of above code should be: 16. But compiler giving the output as 28. Can anyone explain this?

mediocrevegetable1
  • 4,086
  • 1
  • 11
  • 33
  • 4
    Just because `B` can't access them doesn't mean they no longer exist. – 001 Aug 16 '21 at 03:56
  • @JohnnyMopp Okay that means private member of base class is available for derived class. Memory will be allocated for them also for derived class object. But derived class object can't use them because they are private in base class. – Ayush Soni Aug 16 '21 at 04:00
  • Private members of a base class are not accessible *by name*. Access protection applies to names, not data. – molbdnilo Aug 16 '21 at 07:51
  • [Why should I not #include ? - Stack Overflow](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) – Aswin Murali Aug 16 '21 at 15:41

1 Answers1

0

The object of class B has inherited the member variables from class A. For example,

class Car {
private:
string color;
};
class BMW : public Car {
private:
string model;
};

Now, any object of BMW will have its own model and color at the same time. But the color member variable won't be accessible unless you write public getters and setter in the Car class.

  • 1
    Okay that means memory will be allocated for base class private member when we will create object of derived class but we can't access them. Correct me if I am wrong? – Ayush Soni Aug 16 '21 at 04:06