If i have a base class pointer pointing at a derived class
if derived_c redefines a method method()Code:Base_c * b; Derived_c d; b=&d;
if I write b->method() will the derived method be executed?
If i have a base class pointer pointing at a derived class
if derived_c redefines a method method()Code:Base_c * b; Derived_c d; b=&d;
if I write b->method() will the derived method be executed?
try itCode:#include <iostream> class Base_c { void method(){std::cout << "base" << std::endl;} virtual void vMethod(){std:: cout << "base" << std::endl;} }; class Derived_c : Base_c { void method(){std::cout << "derived" << std::endl;} void vMethod(){std::cout << "derived" << std::endl;} } int main() { Base_c *b; Derived_c d; b = &d; b.method(); b.vMethod(); }
It also works with references.Code:#include <iostream> class Base { public: void method(){std::cout << "base" << std::endl;} virtual void vMethod(){std:: cout << "base" << std::endl;} virtual ~Base() {}; }; class Derived: public Base { public: void method(){std::cout << "derived" << std::endl;} virtual void vMethod(){std::cout << "derived" << std::endl;} virtual ~Derived() {}; } int main() { Derived d; Base& b = d; b.method(); b.vMethod(); }
And I would always apply the virtual keyword to a virtual function in a derived class if the base class's function is virtual. The standard may not demand it, but it makes it clearer to the reader.
C_ntua's example is also wrong. It should be:
And since when did you start using T * instead of T*?Code:b->method(); b->vMethod();
sigh, I always make all kind of little mistakes
Wasn't aware of the virtual word for derived class. Agreed, much better using it!
Actually, you do NOT need to put virtual in the derived class - as long as it's declared virtual in the class that it derives from (infinite number of generations back), it will be virtual. Beware tho' that there will be problems if you change the parameters or return type - as it is no longer the same function.
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
By the way, more importantly than failing to use the optional virtual keyword for derived class methods, C_ntua forgot to declare the member functions public and use public inheritance.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Where's the virtual base class destructor?Originally Posted by Elysia
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)