views:

306

answers:

7

Hi everyone:

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?

+10  A: 

That keyword there is strictly optional and makes no difference at all.

UncleBens
It makes no difference to the compiler. To the human reader it may in fact improve readability. I always explicitly state virtual at all levels of inheritance.
Mark B
+7  A: 

The virtual property is inherited from the base class and is assumed to be present even if you don't type it out.

suszterpatt
+1  A: 

The compiler already knows from the 'virtual' keyword in the base class that toString is a virtual method. No need to repeat it.

Patrick
One might add that it might make a difference for the human reader.
sbi
+1  A: 
Abhay
For the case of "to be overridden always", one might want to add the pure specifier as well.
Myke
I think there's meant to be a comma between "overridden" and "always". i.e. "always use the `virtual` keyword" and not "always overridden".
Ben Voigt
@Ben: you are right, Thnx.
Abhay
@Myke: Except that `pure` isn't a C++ keyword.
sbi
The "pure specifier" is of the form = 0, not a keyword.
Myke
@Myke: Well, well. Who would have thought... I didn't, anyway. `:)`
sbi
+12  A: 

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.

Potatoswatter
+1 for quoting actual reference
Daniel
A: 

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.

DoctorT
A: 

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.

fingerprint211b