I have a function X() declared as PURE VIRTUAL in base class:
class Base
{
public:
virtual HRESULT X()=0; // Now it's pure virtual.
.......
};
class Derived_1 : public Base
{
HRESULT X()
{
// body of function X() ; full definition given here as per Derived_1's context. SHOULD WE MAKE THIS VIRTUAL?
}
..................
};
class Derived_2 :public Base
{
HRESULT X()
{
// body of function X() ; full definition given here Derived_2's context. SHOULD WE MAKE THIS VIRTUAL?
}
..................
};
If our intention is to call the function X() generically using a base class pointer, so the decision wheather Derived_1’s or Derived_2’s definition of X() is called, then is it necessary to make the X() in Derived classes Virtual too.
Base * bPtr;
bPtr = new Derived_1(); OR bPtr = new Derived_2(); (Dynamic decision)
bPtr->X()
I feel there is no need to attach the virtual keyword to the definition in Derived classes. Am I right?
Thanks in advance.
The functions in the derived classes will automatically be virtual if the signature of the function (the type of the arguments and return value, identifiers such as const and virtual) in the derived class is identical to the one in your base class. It doesn’t matter whether it is virtual or pure virtual.
So in your example it is not necessary to add virtual for the derived classes.