Can a constructor be virtual in C++? Why or why not?
Last updated
No. Virtual dispatch needs the vptr, but the constructor is what sets it up. Also, constructing an object already requires naming its exact type, so there is nothing to dispatch on.
Use the virtual constructor idiom instead: a virtual
clone()that copies the dynamic type, or a virtualcreate()factory.Destructors can and often should be virtual, because the object is fully constructed by then.
- https://stackoverflow.com/questions/733360/why-do-we-not-have-a-virtual-constructor-in-c
- https://www.geeksforgeeks.org/cpp/advanced-c-virtual-constructor/
- https://www.geeksforgeeks.org/interview-experiences/adobe-interview-experience-for-mts-2-2/
- https://www.geeksforgeeks.org/interview-experiences/adobe-interview-set-16-mts-1/
- https://www.geeksforgeeks.org/cpp/advanced-c-virtual-copy-constructor/
- https://github.com/ahadalireach/oop.interview.questions