Get the App
SLTechnology News&Howtos  ›  Development  › 

What are the polymorphisms and virtual functions of C++?

Shulou Source: shulou.com Published: 2022-06-01 03:19:14 10月25日 Update

This article mainly introduces the relevant knowledge of "what is the polymorphism and virtual function of C++". The editor shows you the operation process through an actual case, and the operation method is simple, fast and practical. I hope this article "what is the polymorphism and virtual function of C++" can help you solve the problem.

Polymorphisms

Polymorphism is one of the key technologies of object-oriented programming. If the programming language does not support polymorphism, it cannot be called an object-oriented language. Using polymorphism technology, functions with the same function name can be called to achieve completely different functions.

There are two polymorphisms in C++:

Polymorphisms at compile time

Through the overloading of functions and operators

Run-time polymorphism

Run-time polymorphism means that before the program is executed, it is impossible to determine which function to call according to the function name and parameters, but must be dynamically determined according to the specific circumstances of the execution of the program; it is achieved through the class inheritance relationship public and virtual functions, and the purpose is to establish a general program; generality is one of the main goals of the program.

Run-time polymorphism can only be achieved through references or pointer calls

Virtual function

A virtual function is a member function of a class and is defined in the following format:

Virtual returns the type function name (parameter table)

The keyword virtual indicates that the member function is a virtual function, and virtual is only used in the class definition. If the virtual function is defined outside the class, virtual cannot be added.

Let's look at the following code

Class Animal {private: string name;public: Animal (const string& na): name (na) {} public: virtual void eat () {} virtual void walk () {} virtual void tail () {} virtual void PrintInfo () {} string& get_name () {return name } const string& get_name () const {return name;}}; class Dog: public Animal {private: string owner;public: Dog (const string& ow, const string na): Animal (na), owner (ow) {} virtual void eat () {cout

Tags: Functions polymorphisms objects pointers polymorphisms members runs dynamics points methods programs categories types procedures compilations differences parameters modes knowledge that is Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi Redmi MySQL Apple Shulou Technology