Aparna Aparna - 1 year ago 128
C++ Question

Virtual Functions

I have this code:

#include <iostream>

using namespace std;

class Polygon {
int width, height;
void set_values (int a, int b)
{ width=a; height=b; }
int area ()
{ return 0; }
void set2_values (int,int);
virtual bool incompressible() const = 0;

bool Polygon::incompressible() const {
return 1;

void Polygon::set2_values (int x, int y) {
width = x;
height = y;

class Rectangle: public Polygon {
int area ()
{ return width * height; }
virtual bool incompressible() const {
return 1;

class Triangle: public Polygon {
int area ()
{ return (width * height / 2); }
bool incompressible() const {
return 0;

int main () {
Rectangle rect;
Triangle trgl;
Polygon poly;
Polygon * ppoly1 = &rect;
Polygon * ppoly2 = &trgl;
Polygon * ppoly3 = &poly;
ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
ppoly3->set_values (4,5);
ppoly3->set2_values (4,5);
cout << ppoly1->area() << '\n';
cout << ppoly3->incompressible() << '\n';
cout << ppoly2->area() << '\n';
cout << ppoly3->area() << '\n';
return 0;

I am getting an error:

cannot declare variable 'poly' to be of abstract type 'Polygon' because the following virtual functions are pure within 'Polygon': virtual bool Polygon::incompressible() const

Can anyone explain why I am getting this error?

Answer Source

The error is self-explanatory. Polygon is an abstract class, because its incompressible() method is abstract. Polygon is providing a default body implementation for incompressible(), but that does not change the fact that incompressible() is declared as abstract in the Polygon class definition.

As such, you simply cannot instantiate an object instance of the abstract Polygon class directly. But that is exactly what your poly variable is trying to do.

You must instantiate a descendant of Polygon that overrides incompressible() so it is not abstract anymore. Which means changing your poly variable to be a Rectangle or Triangle instead of a Polygon. Or just get rid of poly, since your other variables are doing an adequate job of demonstrating the polymorphic nature of the Polygon descendants.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download