I wrote the following code :
#include <iostream>
using namespace std;
class Shape {
public : float lgth;
public : void getLgth() { cin >> lgth;}
};
class Square : public Shape {
public : float calcArea() { return lgth * lgth; }
};
class Circle : public Shape {
public : float calcArea() { return 3.14 * lgth * lgth; }
};
int main() {
char shape_type;
cout <<"Shape Type (c/s) ? ";
cin >> shape_type;
if (shape_type == 'c') {
Circle my_shape;
cout << "Shape Length ? ";
my_shape.getLgth();
cout << "Shape Area : " << my_shape.calcArea() << endl;
}
else if (shape_type == 's') {
Square my_shape;
cout << "Shape Length ? ";
my_shape.getLgth();
cout << "Shape Area : " << my_shape.calcArea() << endl;
}
return 0;
}
As the type of shape is not known at the beginning of the execution (it is asked to user), the variable my_shape is declared in an if then else statement. After this variable is only known in this scope (I understand this point). So, this part of code :
cout << "Shape Length ? ";
my_shape.getLgth();
cout << "Shape Area : " << my_shape.calcArea() << endl;
must be repeated twice in this example.(But more if many shape classes exist).
I am a beginner in C++ but I supposed it is not the best way to do it. Any suggestions would be welcome. Thanks
>Solution :
With template, you might factorize code:
template <typename TShape>
void do_job()
{
TShape my_shape;
std::cout << "Shape Length ?";
my_shape.getLgth();
std::cout << "Shape Area : " << my_shape.calcArea() << std::endl;
}
And in your main:
if (shape_type == 'c') {
do_job<Circle>();
} else if (shape_type == 's') {
do_job<Square>();
}
or with more types
switch (shape_type) {
case 'c': do_job<Circle>(); break;
case 's': do_job<Square>(); break;
// ...
}