-1

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?

Community
  • 1
  • 1
Karl Glaser
  • 829
  • 2
  • 10
  • 17
  • 2
    -1 This question has been asked many times on SO, and you could have found it easily. – Björn Pollex Jul 02 '10 at 14:25
  • I tried but I didn't think to search the word "virtual". Anyway sorry to waste your time if you want me to close it tell me how, but I think the example sums it up well. – Karl Glaser Jul 02 '10 at 14:29
  • just google "calling virtual functions from constructor" you will find **tons** of useful information. I wish i could close the question due to "Use Google first" – Andrey Jul 02 '10 at 14:48

3 Answers3

3

Calling virtual functions inside constructors

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

Community
  • 1
  • 1
Andrey
  • 59,039
  • 12
  • 119
  • 163
2

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
  • 167,383
  • 100
  • 513
  • 979
1

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
  • 95,107
  • 10
  • 109
  • 188
  • 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 Jul 02 '10 at 16:15