The Red Penguin

Inheritance


Tuesday 28 July 2020

Here's a sample .ccp file I worked through which shows how to create a class with constructors and functions, and then a new class which inherits from the first one.
// 1. include to enable me to print to console

#include <iostream>

// 2. define a class called vehicle

class Vehicle
{
public:
// 3. we need to make a constructor
Vehicle();

// 5. we need some functions to do stuff;
float getSpeed();
void accelerate();
void beepHorn();

private:
// 4. it needs to have some data
float speed;
};

// 6. Create a constructor which will initialise speed to 0
Vehicle::Vehicle() : speed(0.0f)
{
}

// 7. Do this to get the speed
float Vehicle::getSpeed()
{
return speed;
}

// 8. Do this to make acceleration
void Vehicle::accelerate()
{
// Note! We put f here to avoid a cast from a double to a float.
// If you write 0.5 instead of 0.5f, you are creating a double, then assigning
// it to a float which involves converting it to a float.
speed += 0.5f;
}

// 9. I think 7, 8 and 9 are functions? Do this to beep horn
void Vehicle::beepHorn()
{
std::cout << "meep meep" << std::endl;
}

// 13. Now I want to add a new type of vehicle called Train.
// This is where inheritance comes in. I can create a new class which
// inherits the properties of Vehicle like this
class Train : public Vehicle
{
public:
// 14. We normally need to initialise a constructor
Train();
// 18. We now want a function to have a different beepHorn
// in Train. So here we initialise the function
void beepHorn();
};

// 15. Now we write the constructor
Train::Train()
{

}

// 19. And here we create the function
void Train::beepHorn()
{
// 20. Train can't see speed, so we need to use the public
// function getSpeed
if (getSpeed() < 0.5f)
{
std::cout << "bip" << std::endl;
}
else
{
std::cout << "BLEEE!!!" << std::endl;
}
}

// 10. To make it all work create the main function
int main()
{
// 11. Create a vehicle v
Vehicle v;
// 12. To call the beepHorn function
v.beepHorn();

// 16. We can now create a train ...
Train t;
// 17. ... and call the beepHorn in Train. We didn't put
// beepHorn in Train because it inherited the properties
// from Vehicles [13]
// Note that Train can access the public stuff in Vehicle
// but not the private stuff, eg it cannot see speed
t.beepHorn();
// 21. To test the new Train beepHorn we can call the
// accelerate function - again, inherited from Vehicle
t.accelerate();
// 22. We can then beep horn again to see what happens
t.beepHorn();
}

// The console prints:
// meep meep (from [12])
// bip [17]
// BLEEE!!! [22]

// Train takes all the properties from Vehicle and extends it,
// by having a different beepHorn based on speed.
// This is a great example of inheritance!