Home > Mobile >  Why does virtual not call the overridden function here?
Why does virtual not call the overridden function here?

Time:09-16

#include <iostream>
struct MemA { virtual void tellClass() { std::cout << "I am member of class A" << std::endl; } };
struct MemB : public MemA { void tellClass() { std::cout << "I am member of class B" << std::endl; } };

class A {
    MemA *current;
public:
    A() : current(new MemA()) {}
    void getMemClass() { current->tellClass(); }
    ~A() { delete current; }
};
class B : public A {
    MemB *current;
public:
    B() : A(), current(new MemB()) {}
    ~B() { delete current; }
};

void main() { B().getMemClass(); }

In the above program I have declared the tellClass() function as virtual which means it should decide which function to call at runtime. Despite that it is printing "I am member of class A" even though I am calling getMemClass() from a class B object which has hidden the MemA *current with MemB *current during inheritence.

How do I get this to work properly?

CodePudding user response:

current in A is a different member from the current in B, i.e. there are two members A::current and B::current. B has both of them as member.

The former is only hidden in as so far as naming current unqualified in the context of class B refers to B::current instead of A::current. In the context of class A (where you are evaluating the call current->tellClass();) the unqualified name still refers to the A::current member.

Data members in C cannot be overridden in the same sense as (virtual) member functions can.

The A::current member of your B object is pointing to a MemA complete object, not a MemB object.

  • Related