I'm reading Effective C++, and there is the "Item 9: Never call virtual functions during construction or destruction". And I'm wondering if my code is fine even if it breaks this rule:
using namespace std;
class A{
public:
A(bool doLog){
if(doLog)
log();
}
virtual void log(){
cout << "logging A\n";
}
};
class B: public A{
public:
B(bool doLog) : A(false){
if(doLog)
log();
}
virtual void log(){
cout << "logging B\n";
}
};
int main() {
A a(true);
B b(true);
}
Is there something wrong with this approach? May I get in trouble when I do something more complicated?
It seams to me that most answers didn't get what I did there, and they simply explained again why is calling virtual function from constructor potentially dangerous.
I would like to stress out that output of my program looks like this:
logging A
logging B
So I get A logged when it is constructed and B logged when it is constructed. And that is what I want! But I'm asking if You find anything wrong(potentially dangerous) with my "hack" to overcome the problem with calling virtual function in constructor.