Question

class A { 
    public: 
    virtual int test()=0; 
};

class B : public A { 
   public: 
   int test(){return 10;}
};


B *b = new B();
b->test(); // would return 10;

whereas:

class A { 
    public: 
    int test(){return 0;}
};

class B : public A { 
   public: 
   int test(){return 10;}
};


B *b = new B();
b->test(); // **would return 0**;

Why does it return "0" here? This makes zero sense to me, because I assume that the (kind of overloaded) members of the derived class (B) come first! What is happening here?

Was it helpful?

Solution

Apart from the invalid syntax (B->test(); where it should be b->test();), the second one will also return 10.

If instead you would have written:

A* a = new B();
a->test();

It would have returned 0 or 10 depending on whether A::test is virtual.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top