Skip to main content

Command Palette

Search for a command to run...

Polymorphism in C++

Published
•3 min read•View as Markdown

What is Polymorphism?

Polymorphism means “many forms“. In C++, it allows a single function or operator to behave differently depending on the context in which it is used. For example, a function makeSound() can behave differently for a Dog object and a Cat object.

Types of Polymorphism

  1. Compile-Time Polymorphism

    This type of polymorphism is resolved during compile time. It includes:

    • Function Overloading: Defining multiple functions with the same name but different parameters.

    • Operator Overloading: Defining custom behavior for operators.

Example of Function Overloading:

    #include <iostream>
    using namespace std;

    class Math {
    public:
        int add(int a, int b) {
            return a + b;
        }

        double add(double a, double b) {
            return a + b;
        }
    };

    int main() {
        Math math;
        cout << math.add(2, 3) << endl;       // Output: 5
        cout << math.add(2.5, 3.5) << endl;   // Output: 6
        return 0;
    }

Runtime Polymorphism

This type of polymorphism is resolved during runtime. It is achieved using:

  • Virtual Functions: Functions in the base class that can be overridden in derived classes.

  • Function Overriding: Redefining a function in a derived class that is already defined in the base class.

Virtual Functions:

A virtual function is a function in a base class that is declared using the virtual keyword. It allows derived classes to provide their own implementation of the function.

Syntax

virtual returnType functionName(parameters) {
    // Base class implementation
}

Function Overriding

Function overriding occurs when a derived class provides a specific implementation of a function that is already defined in its base class.

Rules for Function Overriding:

  1. The function in the derived class must have the same name, return type, and parameters as the function in the base class.

  2. The function in the base class must be declared as virtual.

Example:


#include <iostream>
using namespace std;

class Animal {
public:
    virtual void makeSound() {
        cout << "Animal makes a sound" << endl;
    }
};

class Dog : public Animal {
public:
    void makeSound() override {
        cout << "Dog barks" << endl;
    }
};

class Cat : public Animal {
public:
    void makeSound() override {
        cout << "Cat meows" << endl;
    }
};

int main() {
    Animal* animal1 = new Dog();
    Animal* animal2 = new Cat();

    animal1->makeSound(); // Output: Dog barks
    animal2->makeSound(); // Output: Cat meows

    delete animal1;
    delete animal2;
    return 0;
}

Pure Virtual Functions and Abstract Classes

A pure virtual function is a virtual function with no implementation in the base class. It is declared using = 0.

Syntax

virtual returnType functionName(parameters) = 0;

A class containing at least one pure virtual function is called an abstract class. Abstract classes cannot be instantiated directly.

Example

#include <iostream>
using namespace std;

class Shape {
public:
    virtual void draw() = 0; // Pure virtual function
};

class Circle : public Shape {
public:
    void draw() override {
        cout << "Drawing a Circle" << endl;
    }
};

class Square : public Shape {
public:
    void draw() override {
        cout << "Drawing a Square" << endl;
    }
};

int main() {
    Shape* shape1 = new Circle();
    Shape* shape2 = new Square();

    shape1->draw(); // Output: Drawing a Circle
    shape2->draw(); // Output: Drawing a Square

    delete shape1;
    delete shape2;
    return 0;
}

More from this blog

C++函数 (functions)

函数声明: 函数声明告诉编译器函数的名称,返回类型和参数列表,但不包含函数体。作用: 让编译器知道函数的存在,以便在定义之前使用(通常用于头文件) 允许代码结构更加清晰(函数声明在前,定义在后)。 语法: 返回类型 函数名(参数列表); 函数定义: 函数定义包括函数的完整实现,即包括函数体(代码逻辑)。 语法: 返回类型 函数名(参数列表) { // 函数体(实现代码) return 返回值; // (如果返回类型不是 `void`) } 函数声明和定义的分离: 通...

Mar 10, 20251 min read
C++函数 (functions)

C++数组和向量:

数组 (Array) 数组是固定大小的连续内存块,在编译时确定大小。它们在内存中是静态分配的,意味着大小不可改变。 声明和初始化数组 int arr[5] = {1, 2, 3, 4, 5}; //声明并初始化一个包含5个整数数组 优点: 性能高:数组的访问速度较快,因为它们在内存中是连续的。 内存占用少:没有额外的开销 缺点: 大小固定: 一旦声明,数组的大小不可更改。 不便于扩展:如果需要增加元素,必须手动创建一个新的更大的数组并复制原数组的内容。 std::array (...

Mar 5, 20251 min read
C++数组和向量:

CPP Tutorial

5 posts