views:

45

answers:

3

Possible Duplicate:
Calling virtual functions inside constructors

class Base
    {
    virtual void method()
        { cout << "Run by the base."; };
    public:
    Base() { method(); };
    };

class Derived: public Base
    {
    void method()
        { cout << "Run by the derived."; };
    };

void main()
    {
    Derived();
    }

Output:

Run by the base.

How can one have the derived method run instead, without making a derived constructor?

+2  A: 

You can't since the "derived" part of the object has not been constructed yet so calling a member function from it would be undefined behavior.

sharptooth
+3  A: 

http://stackoverflow.com/questions/962132/calling-virtual-functions-inside-constructors

http://www.artima.com/cppsource/nevercall.html

Andrey
Thank you! x) Lots of useful info.
you should vote to close as exact duplicate
David Rodríguez - dribeas
+1  A: 

You can't do this without adding extra code.

A common way to achieve this is to use a private constructor and a create function that first calls the constructor (via new) and then a second finish_init method on the newly created object. This does prevent you from creating instances of the object on the stack though.

Mark B
Two phase creation of objects is a bad idea. The whole point of constructors is to avoid this. Learn about the PIMPL pattern (available in all good design pattern books).
Martin York