c++ - Polymorphism is not working with function return values of same data type (Base and Inherited class) -


as far know override virtual function in inherited class function should have same data type of return value base class function.

but compiler accept changing return value if return pointer or value belong class inherited class of return value of original function following:

#include <iostream>  class base{ public: virtual  base * clone() {     std::cout << "base::clone()\n" ;     base * bp = new base ;     return bp ; }   std::string id() {return "base class";} };  class derived: public base { public:   //derived* , base* same data type (acceptable):   derived * clone() {     std::cout << "derived::clone()\n" ;     derived * dp = new derived ;     return dp ; }   std::string id() {return "derived class";} };   int main() {    base * bp = new derived;    std::cout << bp->clone()->id() <<"\n";    std::cout << dynamic_cast <derived*>(bp->clone())->id() <<"\n";   /*   next code give error: cannot convert base* derived*:     derived * dp2 = bp->clone();   std::cout << dp2->id() << "\n";   */ } 

the output g++ is:

derived::clone() base class derived::clone() derived class 

overriden clone() function in derived class returned pointer copy of same object on heap. seen output right version of clone() called every time not id(). solve problem had downcast return value desired effect dynamic_cast or make virtual id() in base class.

my question: why polymorphism didn't work in first case

  std::cout << bp->clone()->id() <<"\n"; 

as clone() should return pointer object derived class , consequently id() function of derived class not base class, in case have id() function of base class ?

the polymorphism working in case. reason code printing base class when expect derived class because id() method not virtual.

in order understand happens, have @ code if compiler. in example, bp pointer derived instance has been typed base * in code compiler sees base *. when compiler later in code sees bp->clone() knows clone() method of base class returns base *. when compiler reaches ->id() method call, looks @ base class definition , sees non-virtual method ensures @ runtime, base::id() method called @ location.

if want have polymorphic behaviour, add virtual keyword both id() methods. add override keyword on derived::id() if use c++2011 compliant compiler.


Comments

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -