0

I have a code which is similar to this:

#include <iostream>

class parent
{
public:
    parent()
    //does initializations here
    {
        start();
    }
    virtual void start()=0;
}

class child :public parent
{
public:
    child()
    {}
    void start()
    {
        std::cout << "starting.." << std::endl;
    }
}

Calling the start() function in the constructor of parent class causes a linkage error (unresolved external symbol). I thought this wouldn't be a problem, why does it? Is there an alternative way rather than calling the start() function manually after construction?

Sweeney Todd
  • 880
  • 1
  • 11
  • 25
  • You're calling methods on the derived object before the object is fully constructed – Marco A. Jul 30 '14 at 22:45
  • 1
    After posting the question I found a similar question on right side of the page(i don't know why the search didn't yield those results) – Sweeney Todd Jul 30 '14 at 22:47

1 Answers1

0

Virtual dispatch only works to parts of the object that have been constructed already. In parent's constructor, child does not yet exist, so calling start() calls parent::start.

You can provide a body for it by doing:

void parent::start() {}

although to achieve the call of child::start you would need to call it from child's constructor.

M.M
  • 138,810
  • 21
  • 208
  • 365