Search code examples
c++classvirtualextern

Usage of virtual class and extern in C++


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?


Solution

  • Virtual classes are for when you encounter the dreaded diamond. For example:

    struct Base { int x; };
    struct D1 : Base {};
    struct D2 : Base {};
    struct Derived : D1, D2 {};
    

    Here, Derived actually has two Base parts, and as a result two member variables called x. It will compile, but you might experience some unexpected behaviour when manipulating a Derived object through one of its base classes.

    Derived derived;
    D1& d1 = derived;
    D2& d2 = derived;
    d1.x = 1;
    d2.x = 2;
    cout << d1.x << d2.x << endl; // 12 !
    

    Virtual inheritance solves this problem by making Derived derive from Base only once.

    struct Base { int x; };
    struct D1 : virtual Base {};
    struct D2 : virtual Base {};
    struct Derived : D1, D2 {};
    

    Here, Derived only has one Base part, and one member variable called x.