Constructors should not call virtual functions

I was reading Google Style Code and a section issues the problem of calling virtual functions in the constructor.

I got confused by the statement and asked for help in Stack Overflow. One of the answers explained quite well the problem (the one I chose) and there was another equally useful answer that provided a link of Scott Meyers, one of the most famous gurus of C++ language.

The page is very clear and complete, explaining the problem with examples and pointing a way to avoid it. A very concise way to think about the problem is the following. Suppose you have a class named Base and a class named Derived, that is a subclass of Base. When creating an object of Derived, first the constructor of the base class is called and then the constructor of the derived class is called. While in the base constructor, the object (*this) has the type ‘Base’ and not ‘Derived’. So a calling to virtual function will resolve to the Base class.

Consider the example below:

#include <iostream>
#include <vector>
#include <typeinfo>

class Animal {
    public:
    Animal () {
        std::cout << "My class is: " << typeid(*this).name() << ".\n;
        eat();
    }
    virtual void eat() const { 
        std::cout << "I eat like a generic Animal." << std::endl; 
    }
    virtual ~Animal() {}
};

class Wolf : public Animal {
    public:
        void eat() const { 
            std::cout << "I eat like a wolf!" << std::endl; 
        }
};

int main (){

    Animal a;
    Wolf w;
    return 0;
}

The output of this program is

My class is: 6Animal.
I eat like a generic Animal.
My class is: 6Animal.
I eat like a generic Animal.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

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