Public inheritance means a "is-a" relationship. It means: If B inherits from a in public form, then the B-type object is definitely a object of a, and vice versa. A is an abstraction of B, and B is a special case of a. B can be used in any place where a is used.
However, there are times when mistakes are made in cognition: for example, the function "Fly" is defined for the class bird, but when we derive the Penguin penguin from Bird, we find that the penguin should not fly. What should I do about it.
First, we can modify our design:
Class Bird
{
};
Class Canfly:public Bird
{public
:
virtual void fly ();
Class Cannotfly:public Bird
{
};
Class Penguin:public cannotfly
{
};
Second, we can redefine a fly function for penguins, and then let it produce errors:
Class Bird
{public
:
virtual void Fly () {}
};
Class Penguin
{public
:
void Fly ()
{
throw runtime_error ("Attempt to make a Penguin fly");
}
};
In the calling function:
Penguin p;
try{
p.fly ();
}
catch (const runtime_error &e)
{
cerr<<e.what () <<endl;
}
Its basic idea is that penguins can fly, but the attempt is wrong.
Compared to the first, this is a run-time error that can only be detected when the program is run, and the first is a compile-time error, and the P.fly () itself cannot be invoked.
The third approach is to not define the fly function for penguin so that you can make an error when you try to invoke it.
In short, public inheritance means "is-a", which can be used to call a derived class for a function that calls the base class.