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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the answer! I feel like an idiot now because I should have known this already. Thanks :]
For ways to make something similar happen, see C++ FAQ Lite 23.6: parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.6
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?
@aschepler's link seems to be broken, I think it led to this FAQ
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.