Reputation: 13356
I have a question, here are two classes below:
class Base{
public:
virtual void toString(); // generic implementation
}
class Derive : public Base{
public:
( virtual ) void toString(); // specific implementation
}
The question is:
If I wanna subclass of class Derive perform polymophism using a pointer of type Base, is keyword virtual in the bracket necessary?
If the answer is no, what's the difference between member function toString of class Derive with and without virtual?
Upvotes: 10
Views: 1168
Reputation: 1186
It's a matter of good style, and the user-programmer knows what's going on. In C++0x you can use [[override]] to make it more explicit and visible. You can use [[base_check]] to force the usage of [[override]].
If you don't want or can't do that, simply use the virtual keyword.
If you derive without virtual toString, and you cast an instance of Derive back to Base, calling toString() would actually call Base's toString(), since as far as it know's that's an instance of Base.
Upvotes: 0
Reputation: 7180
A function once a virtual always a virtual.
So in any event if the virtual keyword is not used in the subsequent classes, it does not prevent the function/method from being 'virtual' i.e. be overridden. So the following guideline might help from a team development point-of-view :-
/*virtual*/ void someFunc();
Upvotes: 1
Reputation: 433
It doesn't matter to the compiler whether or not you supply the virtual keyword on derived versions of the function.
However, it's a good idea to supply it anyway, so that anyone looking at your code will be able to tell it's a virtual function.
Upvotes: 0
Reputation: 137770
C++03 §10.3/2:
If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name and same parameter list as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides Base::vf.
Upvotes: 13
Reputation: 23619
The compiler already knows from the 'virtual' keyword in the base class that toString is a virtual method. No need to repeat it.
Upvotes: 1
Reputation: 8273
The virtual
property is inherited from the base class and is assumed to be present even if you don't type it out.
Upvotes: 7
Reputation: 41331
That keyword there is strictly optional and makes no difference at all.
Upvotes: 10