Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C++ Polymorphism

C++ Polymorphism

Polymorphism is one of the important features of C++ object-oriented programming; it means the same interface can exhibit different behaviors depending on the object type.

For example, dogs and cats both belong to animals, and they both have the behavior of making sounds, but dogs bark and cats meow.

In C++, you can define an animal base class Animal, and then create Dog and Cat derived classes. Through the unified interface provided by the base class, you can call the respective behaviors of different animals.

C++ polymorphism is mainly divided into two types:

This chapter mainly introduces runtime polymorphism, including virtual functions, dynamic binding, pure virtual functions, abstract classes, and virtual destructors.

Basic Principles of Polymorphism

In C++, implementing runtime polymorphism usually needs to satisfy the following conditions:

  1. There is an inheritance relationship between the base class and the derived class.
  2. The base class declares a virtual function (virtual).
  3. The derived class overrides the corresponding virtual function.
  4. The virtual function is called through a base class pointer or reference.

For example:

Animal* animal = &dog;

animal->sound();

Although animal Is Animal* type, it actually points to Dog object, so what is called is Dog the sound().

mechanism of selecting the virtual function implementation based on the dynamic type of the object at runtime is calledDynamic Binding.

Example 1: Animal Sound

The following complete example demonstrates how to use virtual functions to implement polymorphism.

Example

#include

using

namespace

std

;

// Animal base class

class

Animal

{

public

:

   

// Define a virtual function

   

virtual

void

sound

(

)

const

{

       

cout

<<

"Animal makes a sound"

<<

endl

;

   

}

   

// Virtual destructor

   

virtual

~Animal

(

)

=

default

;

}

;

// Dog class

class

Dog

:

public

Animal

{

public

:

   

// Override the base class virtual function

   

void

sound

(

)

const

override

{

       

cout

<<

"Dog barks"

<<

endl

;

   

}

}

;

// Cat class

class

Cat

:

public

Animal

{

public

:

   

void

sound

(

)

const

override

{

       

cout

<<

"Cat meows"

<<

endl

;

   

}

}

;

int

main

(

)

{

    Dog dog

;

    Cat cat

;

   

// Base class pointer points to different derived class objects

    Animal

animal

=

&

dog

;

    animal

sound

(

)

;

    animal

=

&

cat

;

    animal

sound

(

)

;

   

return

0

;

}

Program execution result:

Dog barks

Cat meows

Code Analysis

1. Define the base class

Animal class defines the virtual function sound(), allowing derived classes to provide different implementations.

virtual void sound() const {

    cout << "Animal makes a sound" << endl;

}

2. Derived classes override the virtual function

Dog and Cat both inherit from Animal, and use override rewritten sound().

3. Call the function through a base class pointer

When the base class pointer points to Dog object, it calls Dog::sound(); when it points to Cat object, it calls Cat::sound().

Therefore, even if the calling code is the same, the program can still execute different functions based on the actual type of the object.

**Note:** The example uses objects created on the stack, and does not need to use new and delete to manually manage memory.

Example 2: Calculate the Area of Different Shapes

An important use of polymorphism is to handle different types of objects through a unified interface.

For example, both rectangles and triangles need to calculate area, but their area calculation formulas are different.

We can define a Shape base class, providing area() interface, and then different shape classes override the specific calculation method.

Example

#include

using

namespace

std

;

// Shape base class

class

Shape

{

protected

:

   

double

width

;

   

double

height

;

public

:

    Shape

(

double

w,

double

h

)

       

:

width

(

w

)

, height

(

h

)

{

}

   

virtual

double

area

(

)

const

{

       

return

0

;

   

}

   

virtual

~Shape

(

)

=

default

;

}

;

// Rectangle class

class

Rectangle

:

public

Shape

{

public

:

    Rectangle

(

double

w,

double

h

)

       

:

Shape

(

w, h

)

{

}

   

double

area

(

)

const

override

{

       

return

width

height

;

   

}

}

;

// Triangle class

class

Triangle

:

public

Shape

{

public

:

    Triangle

(

double

w,

double

h

)

       

:

Shape

(

w, h

)

{

}

   

double

area

(

)

const

override

{

       

return

width

height

/

2

;

   

}

}

;

int

main

(

)

{

    Rectangle rec

(

10

,

7

)

;

    Triangle tri

(

10

,

5

)

;

    Shape

shape

=

&

rec

;

   

cout

<<

"Rectangle Area: "

<<

shape

area

(

)

<<

endl

;

    shape

=

&

tri

;

   

cout

<<

"Triangle Area: "

<<

shape

area

(

)

<<

endl

;

   

return

0

;

}

Program execution result:

Rectangle Area: 70

Triangle Area: 25

Program analysis:

When adding a new shape type, such as a circle, you only need to inherit from Shape and implement area(), and the existing code that uses Shape interface for calculation usually does not need to be modified.

It should be noted that the above Shape class is not an abstract class, because its area() is a virtual function with a normal implementation, not a pure virtual function.


Virtual Function

A virtual function (Virtual Function) is a non-static member function declared in the base class using the virtual keyword.

Derived classes can override the virtual function so that when the function is called through a base class pointer or reference, the corresponding implementation is selected based on the dynamic type of the object.

For example:

class Base {

public:

    virtual void show() {

        // Base class implementation

    }

};

Virtual functions have the following characteristics:

What happens without virtual?

If a base class member function is not declared as a virtual function, then when it is called through a base class pointer, the version to call is usually determined by the static type of the pointer.

Example

#include

using

namespace

std

;

class

Animal

{

public

:

   

void

sound

(

)

const

{

       

cout

<<

"Animal sound"

<<

endl

;

   

}

}

;

class

Dog

:

public

Animal

{

public

:

   

void

sound

(

)

const

{

       

cout

<<

"Dog barks"

<<

endl

;

   

}

}

;

int

main

(

)

{

    Dog dog

;

    Animal

animal

=

&

dog

;

   

// Called through a base class pointer

    animal

sound

(

)

;

   

// Directly call the derived class function

    dog.

sound

(

)

;

   

return

0

;

}

Execution result:

Animal sound

Dog barks

Because in the base class sound() is not a virtual function, so animal->sound() calls the base class version.

If in the base class's sound() you add virtual, then when called through a base class pointer, the derived class's overriding version can be selected.

override Keyword

Starting from C++11, you can use override to explicitly declare that a derived class function is used to override a base class virtual function.

For example:

class Base {

public:

    virtual void show() const {}

};



class Derived : public Base {

public:

    void show() const override {}

};

override is not a necessary condition for implementing dynamic binding, but it is recommended when overriding virtual functions.

If the function signature does not match, the compiler will report an error. For example:

class Base {

public:

    virtual void show() const {}

};



class Derived : public Base {

public:

    // Compilation error: missing const, cannot override base class function

    void show() override {}

};

This can reduce errors caused by mismatches in parameters,const qualifiers, etc.

final Keyword

Starting from C++11, you can use final Prohibits derived classes from further overriding a virtual function, or prohibits other classes from continuing to inherit from a class.

class Base {

public:

    virtual void show() {}

};



class Derived : public Base {

public:

    void show() final {}

};

In the code above,Derived::show() cannot be overridden by lower-level derived classes.

If final is used for a class:

class Dog final {

public:

    void sound() {}

};

then Dog can no longer be used as a base class for other classes.

using

Dynamic Binding, also known as runtime binding, means the specific implementation of a virtual function call can be determined at program runtime based on the dynamic type of the object.

In contrast is Static Binding, which determines the target of a function call at the compile stage.

Comparison Item Static Binding using
Determination Timing Compile Stage Runtime Stage
Common Scenarios Ordinary member functions, function overloading Virtual function calls through base class pointer or reference
Requires Virtual Function? Not required Usually required
Main Features The call target is usually directly determinable Selects the implementation based on the dynamic type of the object

It should be noted that virtual function calls do not necessarily require dynamic lookup at runtime. When the compiler can determine the target, it may also perform optimizations such as devirtualization.

Virtual Destructor

If a class is used as a polymorphic base class and allows deleting derived class objects through a base class pointer, the base class destructor should usually be declared as virtual.

This ensures that when a derived class object is deleted, the destructors of both the derived class and the base class are executed correctly.

Example

#include

using

namespace

std

;

class

Animal

{

public

:

   

virtual

void

sound

(

)

const

{

       

cout

<<

"Animal sound"

<<

endl

;

   

}

   

// Virtual destructor

   

virtual

~Animal

(

)

{

       

cout

<<

"Animal destroyed"

<<

endl

;

   

}

}

;

class

Dog

:

public

Animal

{

public

:

   

void

sound

(

)

const

override

{

       

cout

<<

"Dog barks"

<<

endl

;

   

}

    ~Dog

(

)

override

{

       

cout

<<

"Dog destroyed"

<<

endl

;

   

}

}

;

int

main

(

)

{

    Animal

animal

=

new

Dog

(

)

;

    animal

sound

(

)

;

   

// Delete the derived class object through the base class pointer

   

delete

animal

;

   

return

0

;

}

Execution result:

Dog barks

Dog destroyed

Animal destroyed

called delete animal will first execute Dog 's destructor, then execute Animal 's destructor.

**Note:** If the base class destructor is not a virtual function, deleting a derived class object through a base class pointer usually produces undefined behavior, not just a simple memory leak.

In modern C++, it is generally recommended to prefer local objects or smart pointers to manage resources, reducing manual use of new and delete.


Pure Virtual Function

A pure virtual function (Pure Virtual Function) is a function specified after the virtual function declaration using = 0 .

Pure virtual functions are usually used to define the base class interface, requiring concrete derived classes to provide their own implementations.

Basic syntax:

virtual 返回类型 函数名(参数列表) = 0;

For example:

class Shape {

public:

    virtual double area() const = 0;

};

A class that contains a pure virtual function that is not yet implemented is an abstract class; objects cannot be created directly.

For example:

Shape shape; // 编译错误:不能实例化抽象类

However, you can declare pointers or references to an abstract class to operate on concrete derived class objects.

Example: Abstract Class and Pure Virtual Function

Below, the area() in the shape class above is changed to a pure virtual function, so that different shape classes must provide a method to calculate the area before they can instantiate objects.

Example

#include

using

namespace

std

;

// Abstract base class

class

Shape

{

public

:

   

// Pure virtual function

   

virtual

double

area

(

)

const

=

0

;

   

virtual

~Shape

(

)

=

default

;

}

;

// Rectangle

class

Rectangle

:

public

Shape

{

private

:

   

double

width

;

   

double

height

;

public

:

    Rectangle

(

double

w,

double

h

)

       

:

width

(

w

)

, height

(

h

)

{

}

   

double

area

(

)

const

override

{

       

return

width

height

;

   

}

}

;

// Triangle

class

Triangle

:

public

Shape

{

private

:

   

double

width

;

   

double

height

;

public

:

    Triangle

(

double

w,

double

h

)

       

:

width

(

w

)

, height

(

h

)

{

}

   

double

area

(

)

const

override

{

       

return

width

height

/

2

;

   

}

}

;

int

main

(

)

{

    Rectangle rec

(

10

,

5

)

;

    Triangle tri

(

10

,

6

)

;

   

// Base class reference can bind to a derived class object

    Shape

&

shape1

=

rec

;

    Shape

&

shape2

=

tri

;

   

cout

<<

"Rectangle Area: "

<<

shape1.

area

(

)

<<

endl

;

   

cout

<<

"Triangle Area: "

<<

shape2.

area

(

)

<<

endl

;

   

return

0

;

}

Program execution result:

Rectangle Area: 50

Triangle Area: 30

Program analysis:

If a derived class does not implement all inherited pure virtual functions, then that derived class is still an abstract class and cannot be instantiated directly.

In addition, a pure virtual function can also be given a function definition outside the class, but this does not change the abstract nature of the class. A pure virtual destructor is a special case; even if declared as = 0, a definition must still be provided.

Differences Between Virtual Functions and Pure Virtual Functions

Comparison Item Virtual Function Pure Virtual Function
Declaration Method virtual void show(); virtual void show() = 0;
Whether Implementation Is Allowed Allowed Allowed to provide a definition outside the class
Whether Derived Classes Must Override Not required Concrete derived classes must provide a non-pure final override
Whether It Makes the Class Abstract Does not become abstract solely because of an ordinary virtual function If there is an unimplemented pure virtual function, it is an abstract class
Main Use Provides overridable behavior Defines an interface that must be implemented by concrete derived classes

Virtual Function Table and Implementation Mechanism

In many C++ compilers, runtime polymorphism is implemented through the virtual function table (Virtual Table, or vtable for short) and the virtual function pointer (usually called vptr).

The virtual function table usually stores information related to virtual function dynamic dispatch, and objects may be associated with the corresponding virtual function table through an internal pointer.

For example:

Animal* animal = &dog;

animal->sound();

The program can find the corresponding sound() implementation based on the dynamic type of the object.

**Note:** The C++ standard specifies the behavior of virtual function calls, but does not mandate that compilers must use a specific virtual function table or virtual function pointer layout.

In addition, ordinary virtual function dynamic dispatch does not depend on RTTI (Runtime Type Information). RTTI is mainly used for dynamic_cast, typeid and other runtime type identification scenarios.

Precautions When Using Polymorphism

In actual C++ development, using polymorphism also requires attention to the following issues:

Polymorphism is suitable for scenarios where different types of objects need to be handled through a unified interface, such as graphics systems, game objects, plugin interfaces, and device drivers.

But not all inheritance relationships require virtual functions. Whether to use runtime polymorphism should be decided based on actual needs.


Summary

C++ polymorphism enables different types of objects to exhibit different behaviors through a unified interface.

In runtime polymorphism, the most important concepts include:

For beginners, it is recommended to first master the relationship between base class pointers, virtual functions, and function overriding, and then further study abstract classes, pure virtual functions, and polymorphic interface design.