by John
Kopp
Introduction Welcome to About.com's
free tutorial on C++ programming. This lesson covers multiple
inheritance. In C++, a class may have multiple base
classes. That is, it may inherit
the members
and methods
of multiple base classes. As an example of this, I will walk
you through some recent design I have done for my top secret
Jet-Car project. Over the last year, tired of both endless
construction on the roads and increased time to pass through
tightened airport security, I have embarked on producing the
only reasonable solution to my commuting nightmares, a
homemade Jet-Car.
As I started on my Jet-Car design, I began with two
existing classes I developed for earlier lessons, the Vehicle
and Car classes.
#include <iostream> using namespace
std;
class Vehicle
{ public: Vehicle() {cout
<< "Vehicle Constructor" <<
endl;} virtual ~Vehicle()
{cout << "Vehicle Destructor" <<
endl;}
virtual void
accelerate() const {cout << "Vehicle Accelerating"
<< endl;}
void
setAcceleration(double a) {acceleration =
a;} double getAcceleration()
const {return acceleration;}
private: double
acceleration; };
class Car: public Vehicle
{ public: Car() {cout
<< "Car Constructor" <<
endl;} virtual ~Car() {cout
<< "Car Destructor" <<
endl;}
virtual void
accelerate() const {cout << "Car Accelerating"
<< endl;} void drive()
const {cout << "Car Driving" <<
endl;}
private: //
Car inherits acceleration accessors,
member };
int main()
{
Car
myCar;
myCar.setAcceleration(9.81);
//One
"G"
cout <<
"Accelerating at " << myCar.getAcceleration()
<< " m/(s*s)"; cout
<<
endl;
myCar.Accelerate(); myCar.Drive();
}
| Next
page > Analysis
of Car Class > Page 1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14
|