C++ virtual functions
Created By: chatGPT
In C++, virtual functions are a key component of polymorphism. They allow you to call derived class methods through a base class reference or pointer, facilitating dynamic dispatch. This means that the function that gets called is determined at runtime based on the object type, rather than the reference type. To declare a virtual function, you use the keyword
virtual
in the base class method declaration. Here's a simple example:class Base {
public:
virtual void show() {
std::cout << "Base class" << std::endl;
}
};
class Derived : public Base {
public:
void show() override {
std::cout << "Derived class" << std::endl;
}
};
In this example,
Base
is the base class with a virtual method named show
. The Derived
class overrides this method. When you call show()
on a base class pointer that points to a derived class object, the derived class's version of the method will execute. Here's how to do that:Base* b;
Derived d;
b = &d;
b->show(); // This will output: "Derived class"
It's important to mention the destructors in relation to virtual functions. If a class declares a virtual function, it should also declare a virtual destructor. This ensures that the correct destructor gets called for derived objects when a base class pointer is used to delete an object. Here's an example:
class Base {
public:
virtual ~Base() {
std::cout << "Base destructor" << std::endl;
}
};
class Derived : public Base {
public:
~Derived() {
std::cout << "Derived destructor" << std::endl;
}
};
Now, if you use a base class pointer to delete a derived class object, the derived class destructor will be called first, followed by the base class destructor. This prevents resource leaks and undefined behavior. Here's how it works:
Base* b = new Derived();
delete b; // This will output: "Derived destructor" followed by "Base destructor"