Game Development Reference
In-Depth Information
C++ supplies classes with a destructor as well as a constructor. Listing 10-9 shows what destructors
for the Vehicle , Car , and Motorcycle classes could look like.
Listing 10-9. Vehicle , Car , and Motorcycle Destructors
Vehicle::~Vehicle()
{
std::cout << "Vehicle Destructed" << std::endl;
}
Car::~Car()
{
std::cout << "Car Destructed" << std::endl;
}
Motorcycle::~Motorcycle()
{
std::cout << "Motorcycle Destructed" << std::endl;
}
Destructors are defined in a similar manner to constructors. They do not have a return value and
they use the name of the class. A destructor is shown to be different from a constructor by having
the ~ symbol added to its name.
If you execute the PrintNumberOfWheels function again with these destructors in place you will see
the following output:
Vehicle Constructed
Vehicle Constructed
Car Constructed
Vehicle Constructed
Motorcycle Constructed
0
4
2
Motorcycle Destructed
Vehicle Destructed
Car Destructed
Vehicle Destructed
Vehicle Destructed
You can deduce a few things from this output. First, you can see that any local variables that are created
from classes are automatically destroyed when the function returns. This is known as going out of
scope. Second, you can see that destructors are called automatically when locally instantiated objects
go out of scope. Third, you can see that the destructors for the base classes are also called; that is,
~Vehicle is called for both Car and Motorcycle . Finally, you should note that the objects are destroyed
in the reverse order in which they were created. The motorcycle object is destroyed before car , which is
destroyed before vehicle . This is a useful feature that we use to our advantage later in this topic.
Method overriding is the final feature of class inheritance you'll learn in this chapter.
 
Search WWH ::




Custom Search