is it possible to call virtual function in constructor ? why we have to not use it in constructor ?
-
I wan to know pros and cons of virtual function use in constructor. i want to know it with real time example.
-
Pros: none.
Cons: it's dangerous, don't do it! Many compilers will warn you against it.
https://isocpp.org/wiki/faq/strange-inheritance#calling-virtuals-from-ctors
https://stackoverflow.com/questions/962132/calling-virtual-functions-inside-constructors
-
Pros: Using it can start interesting conversations with your reviewers
Cons: Dangerous, easy to get wrong, if you get it right it's easy to forget and break later, genuine "gotcha", like the spanish inquisition - nobody expects it.
Example:
class Base { public: Base() { foo(); } void something() { foo(); } virtual void foo() {} }; class Derived : public Base { public: void foo() override {} }; int main() { Derived instance; // calls Base::foo() instance.something(); // calls Derived::foo() }
That's the easiest gotcha and a bug waiting to happen. Usually it's hidden in a lot more code surrounding it and not that easy to spot. With a complicated inheritance structure you could even end up calling a pure virtual base function and that would crash your app.