Is there a difference in these two parts of the code?

#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 have different errors:

error: 'int B::a' is private

error: 'int A::a' is inaccessible

In addition, that errors can be detected, is there any difference in the behavior of these two parts of the code?

+2
source share
2 answers

They are different. In the first case, you create two instances of the variable 'a'. One in the base class, one in the child class. In both examples, you cannot access the variable.

If you have:

A *pA = new B();
pA->a; // This will refer to A::a, which is allowed as it was defined public.

B *pB = new B();
pB->a; // This will refer to B::a, which you can't get access to.

If you want to hide access to the variable "a", I suggest a second example using private inheritance. Keep in mind that private inheritance will also make any functions defined in the base class private.

+2
source

B a, , a, , . B , a a:

#include <stdio.h>

class A {public: int a; };
class B: public A {private: int a;};

int main()
{
    A a;
    B b;
    printf("sizeof(a) == %d, sizeof(b) == %d\n", sizeof(a), sizeof(b));

    b.A::a = 42;
    printf("%d\n", b.A::a);

    return 0;
}
+2

All Articles