Consider the following base class:
class Base
{
public:
virtual ~Base(void);
virtual void foo(void);
virtual void bar(void) = 0;
}
Now suppose I know that a given class should be the most derived class of Base. Should I declare the functions virtual? The most derived class can/will be used polymorphically with Base.
For example, should I use MostDerived1
or MostDerived2
?
class MostDerived1 : public Base
{
public:
~MostDerived1(void);
void foo(void);
void bar(void);
}
class MostDerived2 : public Base
{
public:
virtual ~MostDerived2(void);
virtual void foo(void);
virtual void bar(void);
}
I'm leaning towards MostDerived1 because it most closely models the intent of the programmer: I don't want another child class of MostDerived1 to be used polymorphically with MostDerived1.
Is this reasoning correct? Are there any good reasons why I should pick MostDerived2, aside from the obvious there could be a >0% chance MostDerived2 should be used polymorphically with any deriving classes (class OriginalAssumptionWrong : public MostDerived2)
?
Keep in mind MostDerived1
/ MostDerived2
can both be used polymorphically with Base
.
Adding virtual to derived classes doesn't change their behavior, MostDerived
and MostDerived2
are have exactly the same behavior.
It does however document your intention, however. I would recommend it for that purpose. The override
keyword also helps with this, assuming its available on your platform.
You can't turn off virtual
ness. Another class derived from either MostDerived1
or MostDerived2
can also override any of the virtual
functions regardless of whether you omit the virtual
keyword somewhere in the class hierarchy or not.
If you want to enforce that no other class derives from MostDerived1
, define it as
class MostDerived1 final : public Base
{
// ...
};
The final
keyword can also be used for individual virtual
member functions, ensuring no derived class overrides that specific function.
Once function declear somewhere at the hierarchy as a virtual, it's virtual for ever.
You can use final
or override
if you using C++11
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.