7

My question will probably be best explained by an example.

For example, I have 2 classes: A base class and a derived class:

class baseClass
{
public:
    baseClass()
    {
        foo();
    }
    virtual bool foo() { printf("baseClass"); return false;}

};

class derivedClass : public baseClass
{
public:
    bool foo()
    {
        printf("derivedClass");
        return true;
    }

};

When I create an instance of derivedClass, the constructor in baseClass will be called, and foo() will be called from it's constructor. The problem is, the baseClass' constructor is calling its own foo() and no the overridden foo() that the derived class has overridden. Is there anyway to make the baseClass call the overridden function, not it's own definition of the function?

Brad
  • 10,015
  • 17
  • 54
  • 77

2 Answers2

19

You should not call a virtual method from a constructor because the object has not yet been fully constructed. Essentially, the derived class doesn't exist yet, so its methods cannot be called.

Sydius
  • 13,567
  • 17
  • 59
  • 76
  • Thanks for the answer! I feel like an idiot now because I should have known this already. Thanks :] – Brad Nov 01 '10 at 21:36
  • 2
    For ways to make something similar happen, see C++ FAQ Lite 23.6: http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.6 – aschepler Nov 01 '10 at 21:40
  • Even without the virtual business, I still believe C++ behaves as described in the question. In other words, were it not the constructor being called but an ordinary post-construction method, C++ would still call foo() from the base class(). I know this is an old question, but could you revise your answer addressing this point as well? Or am I just wrong altogether? – weberc2 May 15 '12 at 14:42
  • @aschepler's link seems to be broken, I think it led to [this FAQ](https://isocpp.org/wiki/faq/strange-inheritance#calling-virtuals-from-ctor-idiom) – slawekwin May 17 '17 at 10:31
0

In most languages, this behavior is either prohibited or undefined, with good reason.

Consider this: the base class constructor is run before the subclass constructor, so any vars defined by the sublass will be uninitialized. Are you sure you want to call the subclassed method under those circumstances?

The simplest alternative is to define an initialize() method in your superclass, then just remember to call initialize() from your subclass constructor.

JustinB
  • 793
  • 6
  • 7