Summary of virtual Keyword Usage in C++

Words: 600

virtual is the core mechanism for runtime polymorphism in C++. By default, a function called through a base-class pointer is determined by the static type (compile-time binding); once it is declared virtual, the call is determined by the dynamic type (runtime binding).

cpp
1
2
3
4
5
6
7
8
9
class Animal {
public:
    void speak() { }              // 非虚 —— 静态绑定
    virtual void move() { }       // 虚函数 —— 动态绑定
};

Animal* ptr = new Dog();
ptr->speak();  // 永远调 Animal::speak()
ptr->move();   // 调 Dog::move(),由实际对象类型决定

Virtual Function Table (vtable) and Virtual Function Pointer (vptr)

The compiler generates a virtual function table for every class that contains virtual functions, storing the addresses of the virtual functions. Each instance has a hidden vptr pointing to that table:

1
2
3
4
5
6
对象内存布局:
┌───────────┐
│  vptr     │ ──→ vtable: [ &Base::f, &Base::g, &Base::h ]
├───────────┤
│  成员变量  │
└───────────┘

When a derived class overrides a virtual function, the corresponding slot in its vtable is replaced with the derived-class version. Call path: object → vptr → vtable → function address.

Virtual Destructors

A base-class destructor must be declared virtual; otherwise, when you delete a derived-class object through a base-class pointer, the derived-class destructor will not be called, causing a resource leak:

cpp
1
class Base { public: virtual ~Base() {} };  // 正确做法

Rule of thumb: as long as a class has virtual functions (meaning it is designed as a base class), its destructor should be virtual.

Pure Virtual Functions and Abstract Classes

A pure virtual function is only declared, not implemented, with the syntax = 0. A class containing pure virtual functions is an abstract class and cannot be instantiated; derived classes must implement all pure virtual functions:

cpp
1
2
3
4
5
class Shape {
public:
    virtual double area() const = 0;  // 纯虚函数 = 接口契约
    virtual ~Shape() {}
};

Diamond Inheritance and Virtual Inheritance

Diamond inheritance (D → B,C → A) causes D to contain two copies of A’s data, resulting in an ambiguity error on access:

1
2
3
4
5
   A
  / \
 B   C
  \ /
   D      // D 中有两份 A!

virtual inheritance ensures that the common ancestor exists only once, is placed at the end of the object’s memory, and is accessed indirectly through a vbptr.

Q&A

Q1: Please explain in detail the implementation principle of the C++ virtual function table

A class containing virtual functions generates a virtual function table (vtable) at compile time, and each instance has a virtual function pointer (vptr) pointing to it. At runtime, the virtual function information is found through the vptr, so a base-class pointer can also call the overridden version in the subclass.

Q2: What is the vtable layout under multiple inheritance?

Multiple inheritance stores one vptr for each base class, placed in front of the corresponding base-class data section:

1
vptr1 | base1 | vptr2 | base2 | child

Q3: What additional overhead does virtual inheritance introduce?

Problem solved: Diamond inheritance causes the final class to contain two copies of the common ancestor’s data, and the compiler reports an ambiguity error on access. Virtual inheritance places the common ancestor at the end of memory, and the subclass stores a pointer (vbptr) to the offset of the base class, accessing it through indirect addressing.

Cost:

  • Increased memory (extra vbptr and virtual base class table)
  • Worse performance (one extra indirection)
  • More complex code (the final derived class must manually call the ancestor constructor)

Practical advice: Prefer composition over inheritance; when multiple inheritance is needed, at least one side should be a pure virtual interface class.

This post contains some AI-assisted content, reviewed and edited by the author before publishing.
This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...