Home

C++/CLI Example: An Abstract Class

 

Introduction

This is an example of an abstract class and how to derive a class from it. The abstract class contains a few pure virtual methods and a properties. These methods are implemented in the derived class:

using namespace System;

public ref class CQuadrilateral abstract
{
private:
	double bs;

protected:
	String ^ Name;

public:
	virtual property double Base
	{
		double get() { return bs; }
		void set(double b)
		{
			if( b <= 0 )
				bs = 0.00;
			else
				bs = b;
		}
	}

	virtual String ^ Description();

	virtual double Perimeter() = 0;
	virtual double Area() = 0;
	virtual void   Display() = 0;

	CQuadrilateral();

};

CQuadrilateral::CQuadrilateral()
{
	Name = L"Quadrilateral";
}

String ^ CQuadrilateral::Description()
{
	return L"A quadrilateral is a geometric figure with four sides";
}

public ref class CSquare : public CQuadrilateral
{
public:
	CSquare();

	virtual String ^ Description() new;
	virtual double Perimeter() override;
	virtual double Area() override;
	virtual void   Display() override;
};

CSquare::CSquare()
{
	Name = L"Square";
}

String ^ CSquare::Description()
{
	return L"A square is a quadrilateral with four equal sides";
}

double CSquare::Perimeter()
{
	return 4 * Base;
}

double CSquare::Area()
{
	return Base * Base;
}

void CSquare::Display()
{
	Console::WriteLine(L" === Shape Properties ===");
	Console::WriteLine(L"Name:        {0}", Name);
	Console::WriteLine(L"Description: {0}", CQuadrilateral::Description());
	Console::WriteLine(L"             {0}", Description());
	Console::WriteLine(L"Side:        {0}", Base);
	Console::WriteLine(L"Perimeter:   {0}", Perimeter());
	Console::WriteLine(L"Area:        {0}", Area());
}

int main()
{	
	CSquare ^ sqr = gcnew CSquare;

	sqr->Base = 22.46;
	sqr->Display();

	Console::WriteLine();
	return 0;
}

 

 

Home Copyright © 2006-2016, FunctionX, Inc.