Question:
C++ virtual functions - dose derived func need to be virtual also?
zen29sky
2007-12-17 00:16:49 UTC
If I have a base class:

class Base {
virtual void doSomething();
}

(A) Should my derived class be like this:

class Derived : public Base
{
void doSomething();
}

Or (B) does the derived class also need the work virtual:

class Derived: public Base
{
virtual void doSomething();
}

Would (A) behave differently than (B) ?
Six answers:
DogmaBites
2007-12-17 01:37:01 UTC
As far as the compiler is concerned, both work the same. Once a function is declared as virtual in a base class, all derived class overrides are automatically virtual.



For style, I prefer (B). This way someone reading the derived class immediately understands the function is virtual.



This is one of the warts in C++. A change in the declaration of the base class changes the declaration in derived classes.
Eros
2007-12-17 00:50:36 UTC
Hi,

the right way is (A). You don't need to reuse virtual keyword.

Remember that in C++:

- the default behavior is "a method can not be override", so you need to use the virtual keyword to enable the override;

- a real abstract method (like java abstract keyword) is represented using the "pure function" representation; i.e., an abstract method is:



class Base {

virtual void doSomething() = 0;

}



and so, the derived class must override it.





cheers
Jorge
2007-12-17 00:28:21 UTC
yes it has to be virtual.



I don't think you have to put the keyword virtual....i think it is implied that it is virtual and it will behave that way ....i'm not positive though if you need the keyword or not cuz I always put it its good programming style



if you don't implement B then it is going to automatically inherit the definition for A, then when ever you call doSomething() the right implementation will be picked depending if you call it on the base class or the sub class
viswanathan s
2007-12-17 00:40:24 UTC
Option (A) is correct. Because when u specify virtual keyword in base need not redefine in derived class.
fechter
2016-11-28 04:36:31 UTC
The digital function can define the default habit of the tactic. The caller would not could define it till he desires to alter the habit the place as in organic digital the caller is predicted the define the habit.
Amit R
2007-12-17 00:36:57 UTC
your derived class should look like this:

class Derived: pulic base

{

public override doSomthing();

{

...

}

}



you need to use the override to tell the compiler to use the derived class implementation and no the base class


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...