I’ve been developing in C++ for some time when I was a student, but I never used virtual class or extern in C++ in any of the projects. I just recent read about these two, and was hoping if someone had a better understanding of their usage.
What is the purpose of virtual class? An example of where it could be used/implemented. I gloss over it a bit on IBM website and wrote a test program to see it in action, but when would it be good to use a virtual class?
The same goes for extern as well. I saw an example, and did a test for myself in C++, but what is the advantage of using extern instead of using a header file? And what is the advantage of a header file instead of extern?
Virtual classes are for when you encounter the dreaded diamond. For example:
Here,
Derivedactually has twoBaseparts, and as a result two member variables calledx. It will compile, but you might experience some unexpected behaviour when manipulating aDerivedobject through one of its base classes.Virtual inheritance solves this problem by making
Derivedderive fromBaseonly once.Here,
Derivedonly has oneBasepart, and one member variable calledx.