Example of Abstract class.

In C++, we can make a class abstract by making its function pure virtual. Conversely, a class with no pure virtual function is a concrete class, which object can be instantiated.

A pure virtual represents an abstract behavior and may have not implementation for example draw method in Shape class represent abstract behavior as Shape class itself doesn’t have its existence in real world so there is no question of drawing it however its derived concrete classes like Line, Circle and Triangle does have physical existence and overridden draw method in these classes will have implementation. An example of calculating area is as below.

 

//example of abstract class.
//Calculate Area of a shape.

#include <iostream>

using namespace std;

//Abstract Base Class.
class Area
{
public:

virtual double getArea() = 0; //pure virtual function

void setArea (double d1, double d2)
{
dimention_1 = d1;
dimention_2 = d2;
}

void getDim (double &d1, double &d2)
{
d1 = dimention_1;
d2 = dimention_2;
}

private:
double dimention_1 = 0.0;
double dimention_2 = 0.0;

};

//Public drived class from Area.
class rectangle : public Area
{
public:
double getArea()
{
double d1 = 0.0;
double d2 = 0.0;

getDim (d1, d2);
return (d1*d2);

}
};

//public drived class.
class triangle : public Area
{
public:
double getArea()
{
double d1 = 0.0;
double d2 = 0.0;
getDim(d1, d2);
return (0.5 * d1 * d2);
}
};

//Demo main function
int main()
{
Area *areaPtr;
rectangle rect;
triangle trian;

rect.setArea(23.3, 22.2);
trian.setArea (5, 3.0);

areaPtr = &rect;
cout << “Rectangle has area: ” << areaPtr->getArea () << endl;

areaPtr = &trian;
cout << “Triangle has area: ” << areaPtr->getArea () << endl;

return 0;
}

Advertisements

About Khuram Ali

Programming... Programming and Programming...!!!

Posted on March 21, 2013, in C++ and tagged , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: