Open main menu

CDOT Wiki β

Changes

Virtual Methods and Inheritance

2,013 bytes added, 17:38, 2 October 2012
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ā€¦'
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. <br>'''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:''' <br>(Note that the destructor and hello() method in the derived classes are not explicitly declared to be virtual)
<pre>

#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;

}

</pre>

'''Output:'''

Vehicle pointer to a SportsCar:<br>
Hi, I'm a SportsCar<br>
SportsCar destroyed.<br>
Car destroyed.<br>
Vehicle destroyed.<br>
<br>
Car pointer to a SportsCar:<br>
Hi, I'm a SportsCar<br>
SportsCar destroyed.<br>
Car destroyed.<br>
Vehicle destroyed.<br>
<br>
Vehicle pointer to a Car:<br>
Hi, I'm a Car<br>
Car destroyed.<br>
Vehicle destroyed.<br>



Submitted by: Matt Ashbourne