Access to an overridden member of a base class from a derived class object

I have two classes:

class A { public: int i; }; class B : public A { public: int i; }; 

Suppose I created an object for class B

 B b; 

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

+2
source share
5 answers

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

Yes! What about bA::i ? ;)

+7
source

Yes:

 int main() { B b; bi = 3; bA::i = 5; A *pA = &b; B *pB = &b; std::cout << pA->i << std::endl; std::cout << pB->i << std::endl; } 
+4
source

Yes, you can. Read this to find out.

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

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

base.MyMethod ()

+2
source

Perhaps, as others answered. But in the example you posted, the base and derived members are the same, the data type was not overrated.

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

+2
source

Two ways:

 struct A{ A():i(1){} int i; }; struct B : A{ B():i(0), A(){} int i; }; int main(){ B b; cout << bA::i; cout << (static_cast<A&>(b)).i; } 
+1
source

Source: https://habr.com/ru/post/1432359/


All Articles