Implementing Pure Virtual Functions in C++

By: Reema sen Emailed: 1697 times Printed: 2193 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

Typically, the pure virtual functions in an abstract base class are never implemented. Because no objects of that type are ever created, there is no reason to provide implementations, and the ADT works purely as the definition of an interface to objects which derive from it.

It is possible, however, to provide an implementation to a pure virtual function. The function can then be called by objects derived from the ADT, perhaps to provide common functionality to all the overridden functions. Listing below, this time with Shape as an ADT and with an implementation for the pure virtual function Draw(). The Circle class overrides Draw(), as it must, but it then chains up to the base class function for additional functionality.

In this example, the additional functionality is simply an additional message printed, but one can imagine that the base class provides a shared drawing mechanism, perhaps setting up a window that all derived classes will use.

Implementing pure virtual functions.

1:     //Implementing pure virtual functions
3:     #include <iostream.h>
5:     enum BOOL { FALSE, TRUE };
7:     class Shape
8:     {
9:     public:
10:       Shape(){}
11:       ~Shape(){}
12:       virtual long GetArea() = 0; // error
13:       virtual long GetPerim()= 0;
14:       virtual void Draw() = 0;
15:    private:
16:    };
18:     void Shape::Draw()
19:    {
20:       cout << "Abstract drawing mechanism!\n";
21:    }
23:    class Circle : public Shape
24:    {
25:    public:
26:          Circle(int radius):itsRadius(radius){}
27:          ~Circle(){}
28:          long GetArea() { return 3 * itsRadius * itsRadius; }
29:          long GetPerim() { return 9 * itsRadius; }
30:          void Draw();
31:    private:
32:       int itsRadius;
33:       int itsCircumference;
34:    };
36:    void Circle::Draw()
37:    {
38:       cout << "Circle drawing routine here!\n";
39:       Shape::Draw();
40:    }
43:    class Rectangle : public Shape
44:    {
45:    public:
46:          Rectangle(int len, int width):
47:             itsLength(len), itsWidth(width){}
48:          ~Rectangle(){}
49:          long GetArea() { return itsLength * itsWidth; }
50:          long GetPerim() {return 2*itsLength + 2*itsWidth; }
51:          virtual int GetLength() { return itsLength; }
52:          virtual int GetWidth() { return itsWidth; }
53:          void Draw();
54:    private:
55:       int itsWidth;
56:       int itsLength;
57:    };
59:    void Rectangle::Draw()
60:    {
61:       for (int i = 0; i<itsLength; i++)
62:       {
63:          for (int j = 0; j<itsWidth; j++)
64:             cout << "x ";
66:          cout << "\n";
67:       }
68:       Shape::Draw();
69:    }
72:    class Square : public Rectangle
73:    {
74:    public:
75:          Square(int len);
76:          Square(int len, int width);
77:          ~Square(){}
78:          long GetPerim() {return 4 * GetLength();}
79:    };
81:    Square::Square(int len):
82:       Rectangle(len,len)
83:    {}
85:    Square::Square(int len, int width):
86:       Rectangle(len,width)
88:    {
89:       if (GetLength() != GetWidth())
90:          cout << "Error, not a square... a Rectangle??\n";
91:    }
93:    int main()
94:    {
95:       int choice;
96:       BOOL fQuit = FALSE;
97:       Shape * sp;
99:       while (1)
100:      {
101:         cout << "(1)Circle (2)Rectangle (3)Square (0)Quit: ";
102:         cin >> choice;
104:         switch (choice)
105:         {
106:            case 1: sp = new Circle(5);
107:            break;
108:            case 2: sp = new Rectangle(4,6);
109:            break;
110:            case 3: sp = new Square (5);
111:            break;
112:            default: fQuit = TRUE;
113:            break;
114:         }
115:         if (fQuit)
116:            break;
118:         sp->Draw();
119:         cout << "\n";
120:      }
121:     return 0;
122: }

Output: (1)Circle (2)Rectangle (3)Square (0)Quit: 2
x x x x x x
x x x x x x
x x x x x x
x x x x x x
Abstract drawing mechanism!

(1)Circle (2)Rectangle (3)Square (0)Quit: 3
x x x x x
x x x x x
x x x x x
x x x x x
x x x x x
Abstract drawing mechanism!

(1)Circle (2)Rectangle (3)Square (0)Quit: 0

Analysis: On lines 7-16, the abstract data type Shape is declared, with all three of its accessor methods declared to be pure virtual. Note that this is not necessary. If any one were declared pure virtual, the class would have been an ADT.

The GetArea() and GetPerim() methods are not implemented, but Draw() is. Circle and Rectangle both override Draw(), and both chain up to the base method, taking advantage of shared functionality in the base class.

C++ Home | All C++ Tutorials | Latest C++ Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.

Bookmark and Share


Be the first one to add a comment

Your name (required):

Your email(required, will not be shown to the public):

Your sites URL (optional):

Your comments:

More Tutorials by Reema sen
this keyword sample in Java
Using the DriverManager Class vs Using a DataSource Object for a connection
Steps to get a Free SSL certificate for your Tomcat
fgets(), fputs() - Line Input and Output - sample program in C
Address Arithmetic and pointers in C
Constants and escape sequences in C
Implementing Pure Virtual Functions in C++
strcat() and strncat() sample program in C++
paint() sample program to draw a line in J2ME
Creating and Handling JAR files
SequenceInputStream example program in Java
FilenameFilter - sample program in Java
Transient vs Volatile modifiers in Java
while (1) Loops in C++
Use of 'finally' in Java

More Tutorials in C++
Two-Dimensional Array Manipulation in C++
Calculate average using Two-Dimensional Array in C++
Compute the square root of the sum of the squares of an array in C++
Matrix using nested for loops in C++
Sorting an array of Strings in C++
Calculating total based on the given quantity and price in C++
Compiling and Linking Multiple Source Files in C++
Enumerations in C++
Program to add two numbers in C++
Comments in C++
while loop in C++
for loop in C++
Programming errors a compiler will detect in C++
if in C++
Using the Built-in Arithmetic Types in C++

More Latest News
Most Viewed Articles (in C++ )
Dot (.) vs Arrow (->) to access data members in C++
Using Comments in a C++ Program
Using cout.fill() in C++
Reverse a String in C++
Difference between Procedural, Structured, and Object-Oriented Programming
Demonstration of Prefix and Postfix operators in C++
Constructors and Destructors in C++
while Loops in C++
while (1) Loops in C++
Using switch Statements in C++
The indirection operator (*) - dereference operator.
Stray or Dangling Pointers in C++
Converting C++ Multiple-Inheritance Hierarchies to Java
Operator Precedence in C++
atoi(), itoa() in C++
Most Emailed Articles (in C++)
Using cout in C++
Demonstration of Prefix and Postfix operators in C++
qsort() sample program in C++
Using #define, The Preprocessor and the Compiler in C++
Escape Sequences for Nonprintable Characters in C++
A Brief History of C++
C++ and Object-Oriented Programming
Use of Conditional (Ternary) Operator in C++
Returning values from a function in C++
Constructors and Destructors in C++
Interface Versus Implementation in C++
The Stack and the Free Store in C++
this Pointer in C++
How to handle Exceptions in C++
Using cout.width() in C++