Clause 32: Determine your public inheritance plastic mold out is-a relationship

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.