CKTIS / C++
virtual — virtual functions and virtual inheritance
The virtual keyword has two separate uses: it enables selection of an overriding member function according to an object's dynamic type, and it marks a virtual base class shared within an inheritance hierarchy. Neither mechanism requires the other.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
struct Base {
virtual void f();
virtual void g() = 0;
virtual ~Base() = default;
};
struct Derived : Base {
void f() override;
void g() override;
};
struct Shared : virtual Base {};virtual on a non-static member function's first declaration enables calls to its final overrider according to the object's dynamic type, including through a base pointer or reference. An override remains virtual without repeating virtual; use override so the compiler detects a mismatch. A qualified call such as ref.Base::name() bypasses this dispatch.
The declaration virtual void g() = 0; specifies a pure virtual function. A class whose final overrider remains pure virtual is abstract: you cannot create standalone objects of that class. A pure virtual function can have a separate definition; a pure virtual destructor also requires a definition when called during destruction of derived objects.
If derived objects will be deleted through a base pointer, give the base a public virtual destructor, such as virtual ~Base() = default;. With ordinary delete, without the specialized destroying delete mechanism, lacking a virtual destructor in that situation causes undefined behavior. During construction and destruction, virtual calls on that object do not dispatch to overrides in classes more derived than the class whose constructor or destructor is executing.
Separately, struct Shared : virtual Base {}; specifies virtual inheritance. All virtual inheritance paths to the same base in the most-derived object share one base subobject; non-virtual paths can add separate subobjects. This does not make the base's functions virtual.
The example demonstrates dynamic dispatch and an explicit call to the base implementation. This entry targets C++23; the stated compilation mode does not attest production runtime use. The eel.is source is an evolving working draft, not a frozen C++23 publication.
Examples
#include <iostream>
struct Base {
virtual const char* name() const { return "Base"; }
virtual ~Base() = default;
};
struct Derived : Base {
const char* name() const override { return "Derived"; }
};
int main() {
Derived object;
const Base& ref = object;
std::cout << ref.name() << '\n';
std::cout << ref.Base::name() << '\n';
}
Result
Derived Base
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.