So I know from various online sources that it is generally a no-no to call a virtual function from within a constructor. I realize that the problem here is that the base class will be constructed first and C++ will call the Base class’ version of the function first. However I have a unique use case that might be okay with this. I’d appreciate some comments. Consider this situation.
class Base
{
public:
Base(string data)
{
Parse(data);
}
~Base(){}
private:
virtual Parse(string data);
}
class Derived : public Base
{
public:
Derived(string data)
{
Parse(data);
}
~Derived();
private:
Parse(string data);
}
Let’s say I have a setup like this and my expected behavior of each derived class is that:
- Parse gets called in the base class to parse out what should be common to all these input strings.
- The derived parse should get the data that is specific to the derived class.
Does it make sense to use virtual functions in the constructor in this case? Or am I forced to make “parse” public and call it each time I construct this class? Or are there other suggestions.
I hope this makes sense, and please forgive any syntactical errors above, I’m just trying to express a general idea.
The solution is quite simple:
When
Derivedis constructed, the constructor ofBaseis called before you enter the constructor ofDerived.So the parsing taking place in Base will be finished, and you can finish the parsing in your Derived constructor.