Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to simplify this code where a variable is declared after an user input in c++?

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).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
// ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading