Skip to content
Search

C++:virtual

lastmod 2018-08-17created 2017-02-073 edits

Virtual Table

Using virtual creates a virtual table inside the class.

#include <iostream>
using namespace std;

struct A
{
    A() {}
    ~A() {}
};

struct B
{
    B() {}
    virtual ~B() {}
};

int main()
{
    cout << "size: " << sizeof(A) << endl;
    cout << "size: " << sizeof(B) << endl;
    return 0;
/*OUTPUT:
size: 1
size: 8
*/
}

As shown above, the size of the class actually changes too.

Example

#include <iostream>
using namespace std;

struct A
{
    A() { cout << "A()\n"; }
    /*virtual*/ ~A() { cout << "~A()\n"; }
};

struct B : public A
{
    B() { cout << "B()\n"; }
    ~B() { cout << "~B()\n"; }
};

void test1()
{
    B b1;
/*OUTPUT:
A()
B()
~B()
~A()
*/
}

void test2()
{
    A * b2 = new B();
    delete b2;
/*OUTPUT:
A()
B()
~A()
*/
}

virtual is used to solve the problem seen in test2.

See also