Home > C++11 > Final, Not Virtual

Final, Not Virtual

When writing C++ code, I used to have the habit of tagging every destructor in every class I wrote as “virtual“. I knew that doing so added memory overhead to each object of a class (for storing a pointer to the vtable), but I did it “just in case” I decided to use a class as a base in the future. I was afraid that If I didn’t designate a class dtor as “virtual” from the get go, I might forget to label it as such if I decided later on I needed to use the class as a base.

I have actually made the above mentioned “inheriting-from-a-class-that-doesn’t-have-a-virtual-dtor” mistake several times before – only to discover my faux pas at runtime during unit testing. However, since C++11 added the “final” keyword to the core language to explicitly prevent unintended class derivation (and/or function overriding),  I’ve stopped tagging all my dtors as “virtual“. I now tag all of my newly written classes as “final” from the start. With this new habit, if I later decide to use a “final” class as a base class, my compiler pal will diligently scold me that I can’t inherit from a “final” class. Subsequently, when I remove the “final” tag, it always occurs to me to also change the dtor to “virtual“.

#include <iostream>

class ValueType final {
public:
  ~ValueType() = default;
};

class BaseType {
public:
  virtual ~BaseType() = default;
};

int main() {
  using namespace std;

  cout << " sizeof ValueType = "
       << sizeof(ValueType) << " bytes" << endl
       << " sizeof BaseType = "
       << sizeof(BaseType) << " bytes" << endl;
}

Value Type Size

Categories: C++11 Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: