Virtual functions allow overriding base class functions in derived classes and calling appropriate functions at runtime based on the object type: Create virtual functions: Use the virtual keyword in the base class to declare functions. Override virtual functions: Use the override keyword in derived classes to override base class virtual functions. Actual call: When a derived class object is pointed to through a base class pointer or reference, the overridden version will be called. Uncovered virtual function: If not overridden, the base class original implementation will be called. Call using pointers or references: Implement polymorphism, allowing a pointer or reference from a base class to point to a derived class object, and call the appropriate overriding function at runtime.
Virtual functions are a type of polymorphism in C mechanism. It allows functions in the base class to be overridden in the derived class, allowing the appropriate function to be called at runtime based on the actual type of the object.
To create a virtual function, you need to declare the function in the base class using the virtual
keyword, as follows:
class Base { public: virtual void print() { cout << "Base class" << endl; } };
In derived classes, you can use the override
keyword to override virtual functions in the base class, as shown below:
class Derived : public Base { public: override void print() { cout << "Derived class" << endl; } };
Consider the following simple example:
#include <iostream> using namespace std; class Animal { public: virtual void speak() { cout << "Animal speaks" << endl; } }; class Dog : public Animal { public: override void speak() { cout << "Dog barks" << endl; } }; int main() { Animal* a = new Dog(); a->speak(); // 输出:Dog barks return 0; }
In this example, the base class Animal
defines the speak()
virtual function, which is used in Dog
Overridden in derived classes. When we call the speak()
function via the Animal*
pointer, the overridden version is called, outputting "Dog barks".
Q: Why do I need to use pointers or references to call virtual functions?
Answer: To achieve polymorphism, a pointer or reference from a base class can point to an object of a derived class, allowing the appropriate overriding function to be called at runtime.
Q: What happens if the virtual function is not overridden in the derived class?
Answer: In this case, the original implementation in the base class will be called.
The above is the detailed content of Practical application of C++ virtual functions: code examples and troubleshooting. For more information, please follow other related articles on the PHP Chinese website!