开发者

Accessing overridden base class member from derived class object

I have two classes:

class A
{
public:
  int i;
};

class B : p开发者_运维知识库ublic A
{
public:
  int i;
};

Suppose that I created an object for class B

B b;

Is it possible to access A::i using b?


Is it possible to access A::i using b?

Yes! How about b.A::i? ;)


Yes:

int main()
{
    B b;

    b.i = 3;
    b.A::i = 5;

    A *pA = &b;
    B *pB = &b;
    std::cout << pA->i << std::endl;
    std::cout << pB->i << std::endl;
}


Yes you can. To find out read this

An override method provides a new implementation of a member inherited from a base class. The method overridden by an override declaration is known as the overridden base method. The overridden base method must have the same signature as the override method.

From within the derived class that has an override method, you still can access the overridden base method that has the same name by using the base keyword. For example, if you have a virtual method MyMethod(), and an override method on a derived class, you can access the virtual method from the derived class by using the call:

base.MyMethod()


Two ways:

struct A{
    A():i(1){}
    int i;
};

struct B : A{
    B():i(0), A(){}
    int i;
};

int main(){
    B b;
    cout << b.A::i;
    cout << (static_cast<A&>(b)).i;
}


It is possible, as others replied. But in the example you posted, the base and derived members are the same, the data type was not overriden.

This would be relevant in the case of derived classes that define a new data type for the base members as shown in this post: C++ Inheritance. Changing Object data Types

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜