When it comes to virtual functions, if anyone who has n’t touched the concept first sees it, it must be a face of aggression. But in fact, virtual functions have a lot of uses, the following introduces the uses of common virtual functions.
Virtual function:
Let me briefly talk about the concept of virtual functions. Those member functions that are modified by the virtual keyword are virtual functions. The function of the virtual function is explained in technical terms to achieve polymorphism, which separates the interface from the implementation. The popular explanation is that the same function has different implementations, but uses different strategies due to individual differences. Let's look at a simple piece of code:
class Base {
public:
virtual void foo () {cout << "Base :: foo () is called" << endl;}
};
class Derived: public Base {
public:
void foo () {cout << "Derived :: foo () is called" << endl;}
};
int main (void) {
Base * b = new Derived ();
b-> foo (); // b is a pointer of type Base, but actually points to the Derived class, so the function foo called is of the Derived class
return 0;
}
Pure virtual function:
A pure virtual function is a virtual function declared in a base class. It is not defined in the base class, but requires any derived class to define its own implementation method. The method of implementing pure virtual functions in the base class is to add "= 0" after the function prototype, for example:
virtual void func () = 0;
Classes with pure virtual functions cannot be instantiated. What is the significance of the existence of pure virtual functions?
Many times, it is unreasonable for the base class itself to generate objects. For example, animals as a base class can derive monkeys, dogs, cats and other subclasses, but it is obviously unreasonable for animals to directly generate objects, so we generally declare animals as pure base classes.
Declare virtual destructor for base class
When a derived class object is deleted via a base class pointer and the base class carries a non-virtual destructor, the result is undefined. However, in general, the derived component of the object is not destroyed, and the base class is destroyed. Cause an error.
Destructor call operation: The most derived class whose destructor is called first, then the destructor of each base class is called.
Neither the standard string nor the STL container is designed to be used as a base class, let alone polymorphism.
Contact: Manager Xu
Phone: 13907330718
Tel: 0731-22222718
Email: hniatcom@163.com
Add: Room 603, 6th Floor, Shifting Room, No. 2, Orbit Zhigu, No. 79 Liancheng Road, Shifeng District, Zhuzhou City, Hunan Province