To realize Polymorphism, we need to use a base class pointer to a derived class instance. Everything about polymorphism is good except, what if every derived class has one or several its own member function? If the base class pointer cannot access these derived class member function, then what is so convenient about polymorphism?
Below is an example. "shape" is a base class. "square" and "circle" are two derived classes.
class shape {
public:
virtual void getArea()=0;
};
class square: public shape {
private:
int edge;
public:
square(){edge = 1;}
virtual void getArea(){ //polymorphism
cout << edge*edge << "\n";
}
void getNumberOfEdge(){ //a new member function
cout << "4\n";
}
};
class circle: public shape {
private:
int radius;
public:
circle(){radius = 1;}
virtual void getArea(){ //polymorphism
cout << 3*radius*radius << "\n";
}
void getCurvature(){ //a new member function
cout << 1/radius << "\n";
}
};
int main(){
shape* arr[2] = {
new square(),
new circle()
};
arr[0]->getArea();
arr[1]->getArea();
arr[0]->getNumberOfEdge(); //compiler error
}
getArea() is a good example of realizing polymorphism. However accessing derived class member function gives me compiler error, which I understand why perfectly. But from a designing point of view, we do not want to add a bunch of virtual functions to the base class just for the sake of each derived class, right?
std::unique_ptrinstead.