C++: Simple Inheritance
Although the lesson is called "Simple Inheritance" its not really as simple as it sounds.
In fact I would say its pretty difficult.
What simple inheritance does is stop you from having to keep using the same code, in our example we would need to repeat the code that is in "ElectronicFish" into "Cod" and "Haddock" for them to work without inheritance.
Take a look at this code and we will talk about it afterwards:
#include <iostream>
using namespace std;
class ElectronicFish
{
public:
ElectronicFish(){
bIsOn = false;
}
bool IsOn(){
return bIsOn;
}
void TurnOff(){
bIsOn = false;
}
void TurnOn(){
bIsOn = true;
}
private:
bool bIsOn;
};
class Cod : public ElectronicFish
{
};
class Haddock : public ElectronicFish
{
};
int main(){
Cod MyCod;
Haddock MyHaddock;
cout << "Is the Cod on: " << MyCod.IsOn() << endl;
MyCod.TurnOn();
cout << "Is the Cod on: " << MyCod.IsOn() << endl;
MyCod.TurnOff();
cout << "Is the Cod on: " << MyCod.IsOn() << endl;
cout << "Is the Haddock on: " << MyHaddock.IsOn() << endl;
MyHaddock.TurnOn();
cout << "Is the Haddock on: " << MyHaddock.IsOn() << endl;
MyHaddock.TurnOff();
cout << "Is the Haddock on: " << MyHaddock.IsOn() << endl;
system("PAUSE");
return 0;
}
The basic bits that you wont understand are bits like this:
class Cod : public ElectronicFish
{
All this does is say that the class cod, is inherited from the class "ElectronicFish".
The Cod and Haddock's codes arn't too difficult, but lets go through the whole ElectronicFish code:
class ElectronicFish
{
public:
ElectronicFish(){
bIsOn = false;
}
All this does is create the Electronic fish class, and in the constructor sets the bIsOn variable to false.
bool IsOn(){
return bIsOn;
}
The above simply is the IsOn function, which returns the boolean bIsOn (much like the Get functions in the previous lessons).
void TurnOff(){
bIsOn = false;
}
void TurnOn(){
bIsOn = true;
}
The above functions are also self explanatory, they simply change the value of the boolean bIsOn.
Don't worry if you don't quite understand this yet, re-read the lesson a few times, and you will eventually pick it up, try creating your own inheritance code, its dead easy once you figure it out.
Back to C++

