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?
Printable View
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?
Not unless the base class has the method, as well.
Preferably it should be virtual as well, so that Derived::method is called instead of Base::method.
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
As I said, the standard may not demand it, but I consider it good practice.
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.
Horrors o_O
That's what I get for copying an example.
At least mine shall be correct.
Where's the virtual base class destructor? ;)Quote:
Originally Posted by Elysia
I don't see a missing virtual destructor, do you? :p