c++ - Can a base class pointer which points to an object of derived class be made to access a new member which was derclared in the derived class? -
I have written the following code, where I created a base square pointer which indicates the object class of the derived class type. I member using the inherited arrow operator from the base. But whenever I tried to use a member I defined in the derived class, I get an error. The code is below
# include & lt; Iostream & gt; using namespace std; Structure A {}; Structure B: A {int b; B (): B (5) {}}; Int main () {b y; A * ptr = & amp; Y; The court's & lt; & Lt; Ptr- & gt; B & lt; & Lt; Endl; No, it will not be able to access the declared member in the derived class.
No, it will not be able to access the declared member in the derived class. When you use ptr-> B, the compiler sees for member B in class A because the indicator is a square A * and A is not the name of any member, resulting in an error.
The compiler does not know which object can point at pointers run time.
Comments
Post a Comment