#include<stdio.h>
class A {public: int a; };
class B: public A {private: int a;};
int main(){
B b;
printf("%d", b.a);
return 0;
}
#include<stdio.h>
class A {public: int a; };
class B: private A {};
int main(){
B b;
printf("%d", b.a);
return 0;
}
I ask because I get different errors:
error: 'int B::a' is private
error: 'int A::a' is inaccessible
Apart from what the errors might reveal, is there any difference at all in the behaviour of these two pieces of code?
They are different. In the first instance, you are creating two instances of the variable ‘a’. One in the base class, one in the child class. In both examples you can’t get access to the variable.
If you have:
If you want to hide access to the ‘a’ variable, I suggest the second example, using private inheritance. Be aware that private inheritance will also make any functions defined in the base class private.