I’m wondering whether this implementation of polymorphism is desirable in C++.
I have a superclass (cPolygon) and two subclasses (cRectangle and cTriangle).
The question is whether it’s considered good form to implement a method in one of the subclasses that is not included in the superclass ie. should I be creating the
setSomething method only in cRectangle? If I do so, should I also create this method in the superclass cPolygon as well (obviously not abstract though)?
Thanks guys
Pete
#include <iostream>
using namespace std;
// Super class
class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; }
};
// Sublcass Rectangle
class CRectangle: public CPolygon {
public:
int area ()
{ return (width * height); }
// Method only present in rectangle.
// Is this OK?
void setSomething(int a) {
_a = a;
}
private:
int _a;
};
// Subclass Triangle
class CTriangle: public CPolygon {
public:
int area ()
{ return (width * height / 2); }
};
int main () {
CRectangle rect;
CTriangle trgl;
CPolygon * ppoly1 = ▭
CPolygon * ppoly2 = &trgl;
// Is this OK?
rect->setSomething(3);
trgl->set_values(2,3);
ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
cout << rect.area() << endl;
cout << trgl.area() << endl;
return 0;
}
It is possible and completely valid to have new methods in the subclass which are not available in the super class.
But in such cases, you will not be able to call it using a base class pointer or reference, even though it points to the correct subclass object.
You can however cast the pointer or reference to the subclass to call that method, but casting is the root of many bugs and should be avoided.