# Polymorphism Question

For the sake of the question I've taken this code from http://www.cplusplus.com/doc/tutorial/polymorphism/

``````class Polygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; }
};

class Rectangle: public Polygon {
public:
int area()
{ return width*height; }
};

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

int main () {
Rectangle rect;
Triangle trgl;
Polygon * ppoly1 = &rect;
Polygon * ppoly2 = &trgl;
ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
return 0;
}
``````

Is it possible to create a Polygon array and store Triangle and Rectangle objects in it and still be possible to access the functions associated with their respective classes?

For example:

``````Polygon *array[2];
array[0] = new Triangle;
array[1] = new Rectangle;
``````

Is there any way to call area() from the Polygon array?

No, the access to the functions is restricted to base class functions only.

But there's easy way to fix this problem, by providing pure virtual function in the base class:

``````class Polygon {
public:
virtual int area()=0;
};
``````

Then it'll just work fine.

• That's a real bummer, I guess I'm going to have to think of a different way to structure my program. – Jacob Bauer Feb 27 '15 at 23:39
• Your example is almost exactly valid polymorphism example, except that Rectangle and Triangle are missing constructors with additional parameters. – tp1 Feb 27 '15 at 23:55
• @JacobBauer What's wrong with adding the pure virtual function? That's the only easy way to get runtime polymorphism, which is what you appear to be asking for. – Ixrec Feb 28 '15 at 1:03
• In the original example, `Rectangle::area` and `Triangle::area` are completely unrelated to each other, and non-virtual. In order for them to be related to each other, you need a common base class with a virtual method of the same name to tell the compiler to build the runtime table that makes polymorphism work. – Gort the Robot Feb 28 '15 at 3:23
• @JacobBauer it still has the function, you just can't access it, and it's not the same function as `Rectangle`'s `area` function. Adding the function to the base class as well (it must be virtual, and it can optionally be pure virtual) is the solution - it does exactly what you want. – user253751 Feb 28 '15 at 9:05