Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I declare all functions virtual in a base class?

Tags:

c++

When I declare a base class, should I declare all the functions in it as virtual, or should I have a set of virtual functions and a set of non-virtual functions which I am sure are not going to be inherited?

like image 332
excray Avatar asked May 07 '09 12:05

excray


4 Answers

A function only needs to be virtual iff a derived class will implement that function in a different way.

For example:

class Base {
public:
  void setI (int i)  // No need for it to be virtual
  {
    m_i = i;
  }

  virtual ~Base () {}         // Almost always a good idea

  virtual bool isDerived1 ()  // Is overridden - so make it virtual
  {
    return false;
  }

private:
  int m_i;
};

class Derived1 : public Base {
public:
  virtual ~Derived () {}

  virtual bool isDerived1 ()  // Is overridden - so make it virtual
  {
    return true;
  }
};

As a result, I would error the side of not having anything virtual unless you know in advance that you intend to override it or until you discover that you require the behaviour. The only exception to this is the destructor, for which its almost always the case that you want it to be virtual in a base class.

like image 171
Richard Corden Avatar answered Nov 15 '22 13:11

Richard Corden


You should only make functions you intend and design to be overridden virtual. Making a method virtual is not free in terms of both maintenance and performance (maintenance being the much bigger issue IMHO).

Once a method is virtual it becomes harder to reason about any code which uses this method. Because instead of considering what one method call would do, you must consider what N method calls would do in that scenario. N represents the number of sub classes which override that method.

The one exception to this rule is destructors. They should be virtual in any class which is intended to be derived from. It's the only way to guarantee that the proper destructor is called during deallocation.

like image 44
JaredPar Avatar answered Nov 15 '22 12:11

JaredPar


The non-virtual interface idiom (C++ Coding Standards item 39) says that a base class should have non-virtual interface methods, allowing the base class to guarantee invariants, and non-public virtual methods for customization of the base class behaviour by derived classes. The non-virtual interface methods call the virtual methods to provide the overridable behaviour.

like image 34
andreas buykx Avatar answered Nov 15 '22 13:11

andreas buykx


I tend to make only the things I want to be overridable virtual. If my initial assumptions about what I will want to override turn out to be wrong, I go back and change the base class.

Oh, and obviously always make your destructor virtual if you're working on something that will be inherited from.

like image 29
Dominic Rodger Avatar answered Nov 15 '22 14:11

Dominic Rodger