views:

89

answers:

4

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?

+2  A: 

This is by design in C++, see the C++ FAQ.

In your case i also don't see why you would need it - if you want to use an initialization helper function, there is no need for it to be virtual.

Georg Fritzsche
A: 

It appears you want your base type's constructor to call down into the derived type through a virtual method. This is troublesome as the derived type hasn't yet been fully constructed. What is the derived type's overridden virtual function going to use for state when its type hasn't yet been constructed? You might want to look into another design pattern, such as a factory, that can encapsulate the two-step construct/initialize pattern if you really need it.

Curt Nichols
+1  A: 

Your explanation is here in Scott Meyer's Effective C++

Don't call virtual functions during construction or destruction, because such calls will never go to a more derived class than that of the currently executing constructor or destructor.

Romain Hippeau
+3  A: 

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.

Billy ONeal