乐闻世界logo
搜索文章和话题

What is a pure virtual function?

1个答案

1

Pure virtual functions are a concept in C++ used to define abstract classes. They have no function body and only declare the function's interface, with the purpose of requiring derived classes to implement specific functionality.

In C++, if a class contains at least one pure virtual function, it is considered an abstract class. Abstract classes cannot be instantiated, meaning objects of such a class cannot be created. Pure virtual functions are declared in a class by adding = 0 at the end of the function declaration.

For example:

cpp
class Animal { public: virtual void speak() = 0; // pure virtual function };

In this example, Animal is an abstract class containing a pure virtual function speak(). Because speak() is pure virtual, it enforces that any derived class inheriting from Animal must provide a concrete implementation of speak(). This approach defines a unified interface, while the concrete implementation is delegated to the subclasses.

We can create subclasses inheriting from Animal to implement this function:

cpp
class Dog : public Animal { public: void speak() override { cout << "Woof!" << endl; } }; class Cat : public Animal { public: void speak() override { cout << "Meow!" << endl; } };

Here, Dog and Cat classes inherit from Animal and provide concrete implementations of speak(). Each subclass defines the specific behavior of speak() based on its own characteristics, which is an example of polymorphism.

2024年7月23日 11:01 回复

你的答案