You're welcome.
As Computergeek01 points out you can add more data and function members to the base class then access these in either the base or derived classes through a pointer to the base class.
You can't use a pointer to the base class to
directly access data or function members which are not inherited from the base class, but you can still manipulate the non-inherited members through virtual versions of the base class functions.
I am avoiding work on my own project today, so I put together another example here to show that.
Suppose that the food class is not meant to model any
particular food. It describes only things common to
all foods. It seems appropriate to make food an abstract class:
1 2 3 4 5 6 7
|
// no particular food type implied
class food// abstract class
{
public:
int bitesLeft;// a property of all foods
virtual void eat(void) = 0;// something you must do with food.
};
|
Now a class for a particular food item. Burgers!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
// burger is a type of food
class burger: public food// MUST implement the eat()
{
public:
void eat(void)
{
if( bitesLeft > 0 )
{
cout << "Taking a bite of burger.";
bitesLeft--;
cout << " bitesLeft = " << bitesLeft;
if( bitesLeft == 0 )
cout << " The burger is now eaten!";
}
}
};
|
Now for something which is not food, but goes with food sometimes. An unrelated class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
class soda// goes with the burger in a meal
{
public:
int sipsLeft;
void drink(void)
{
if( sipsLeft > 0 )
{
cout << " and a sip of soda.";
sipsLeft--;
cout << " sipsLeft = " << sipsLeft;
if( sipsLeft == 0 )
cout << endl << " Soda is now empty";
}
else
cout << endl << "Damn! The soda is empty";
}
};
|
Next, let's make a meal from a burger and a soda
1 2 3 4 5 6 7 8 9 10 11 12
|
// meal inherits a burger then adds a soda
class meal: public burger// food is now an indirect base class of meal
{
public:
soda mySoda;
void eat(void)// meal version of the eat()
{
burger::eat();// calling burger version of the eat()
if( bitesLeft%3 == 0 )// sip soda every 3rd bite
mySoda.drink();
}
};
|
Lets eat the meal using a food*, to show we can manipulate an object (soda) which is unrelated to food through the food*:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
int main(void)
{
meal m;
m.bitesLeft = 12;
m.mySoda.sipsLeft = 3;
food* pf = &m;
while( pf->bitesLeft )// eat until the food is gone
pf->eat();
cout << endl;
return 0;
}
|
These are some really cool tools we can work with here!!