0
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?

user1511417
  • 1,880
  • 3
  • 20
  • 41

1 Answers1

4

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.

user1610015
  • 6,561
  • 2
  • 15
  • 18
  • Go to: http://www.cplusplus.com/doc/tutorial/polymorphism/ and Ctrl+F "varify" and see the above example. Now If I make the base virtual funtion not virtual and allocate "ppoly1" not as a Polygon, but as a CRectangle, it will return 0! – user1511417 Feb 12 '13 at 19:39
  • @user1511417: Take the time to reread the code in the linked page. You will only get the base's implementation if the static type of the pointer/reference is *base* – David Rodríguez - dribeas Feb 12 '13 at 19:46