Demo entry 1074182

Pointers to base class

   

Submitted by Sachin Yadav on Jan 14, 2015 at 12:50
Language: C++. Code size: 676 Bytes.

#include 
using namespace std;

class CPoly
{
	protected:
		int width, height;
	public:
		void setup (int first, int second)
		{
			width= first;
			height= second;
		}
};

class CRectangle: public CPoly
{
	public:
		int area()
		{
			return (width * height);
		}
};

class CTriangle: public CPoly
{
	public:
		int area()
		{
			return (width * height / 2);
		}
}; 

int main ()
{
	CRectangle rectangle;
	CTriangle triangle;

	CPoly * ptr_polygon1 = &rectangle;
	CPoly * ptr_polygon2 = ?

	ptr_polygon1->setup(2,2);
	ptr_polygon2->setup(2,2);

	cout << rectangle.area () << endl;
	cout << triangle.area () << endl;

	return 0;
}

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).