Search code examples
c++classpolymorphismvirtual

Virtual class problem


What i think about virtual class is, if a derived class has a public base, let's say, class base, then a pointer to derived can be assigned to a variable of type pointer to base without use of any explicit type conversion. But what if, we are inside of base class then how can we call derived class's functions. I will give an example:

class Graph{
  public:
    Graph(string);
    virtual bool addEdge(string,string);
}
class Direct:public Graph{
  public:  
    Direct(string);
    bool addEdge(string,string);
}
Direct::Direct(string filename):Graph(filename){};

When i call constructor of Direct class then it calls Graph. Now lets think Graph function calls addedge.

Graph(string str){
    addedge(str,str);
}

When it calls addedge, even if the function is virtual, it calls Graph::edge. What i want is, to call Direct::addedge. How can it be done?


Solution

  • It can't be done. Virtual functions cannot be called whithin constructors -- at least they cannot be called with virtual behavior. The problem is that the derived class constructor is responsible for setting up the vtbl to point to it's particular instance of the virtual functions. The base class' constructor is executed first, before the derived constructor, so a direct solution to this is not possible.

    You can work around this using either some form of "init" function on your base class, or you can use a factory method.