开发者

Is there any difference these two pieces of 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; };
c开发者_高级运维lass 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:

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 '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.


In your first example, class B has two members named a, the one that it inherits from class A and the one that it defines itself. An object of class B ends up being larger as a result, and you can still access class A's a member explicitly:

#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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜