Difference between revisions of "Virtual Methods and Inheritance"
(Created page with 'When a base class declares a method as virtual, all implementations of that method in derived classes are automatically virtual. The destructor is treated in the same way. If the…') |
(No difference)
|
Latest revision as of 17:38, 2 October 2012
When a base class declares a method as virtual, all implementations of that method in derived classes are automatically virtual. The destructor is treated in the same way. If the base class has a virtual destructor, so will all derived classes.
If a method is virtual in the base class, all derived implementations are also virtual even if not explicitly declared so in the derived class.
Example:
(Note that the destructor and hello() method in the derived classes are not explicitly declared to be virtual)
#include <iostream> using namespace std; class Vehicle { public: Vehicle() {} virtual ~Vehicle() { cout << "Vehicle destroyed." << endl; } virtual void hello() { cout << "Hi, I'm a Vehicle" << endl; } }; class Car : public Vehicle { public: Car() {} ~Car() { cout << "Car destroyed." << endl; } void hello() { cout << "Hi, I'm a Car" << endl; } }; class SportsCar : public Car { public: SportsCar() {} ~SportsCar() { cout << "SportsCar destroyed." << endl; } void hello() { cout << "Hi, I'm a SportsCar" << endl; } }; int main() { cout << "Vehicle pointer to a SportsCar:" << endl; Vehicle *dbs = new SportsCar(); dbs->hello(); delete dbs; cout << endl << "Car pointer to a SportsCar:" << endl; Car *m5 = new SportsCar(); m5->hello(); delete m5; cout << endl << "Vehicle pointer to a Car:" << endl; Vehicle *civic = new Car(); civic->hello(); delete m5; return 0; }
Output:
Vehicle pointer to a SportsCar:
Hi, I'm a SportsCar
SportsCar destroyed.
Car destroyed.
Vehicle destroyed.
Car pointer to a SportsCar:
Hi, I'm a SportsCar
SportsCar destroyed.
Car destroyed.
Vehicle destroyed.
Vehicle pointer to a Car:
Hi, I'm a Car
Car destroyed.
Vehicle destroyed.
Submitted by: Matt Ashbourne