Search code examples
c++classobjectsetteruser-data

Is there a way to pass user data for a setter without using an extra variable in C++?


I'm still new to C++ and so far I used to pass static values to setter methods. Now I'm trying to pass user data to the methods, but so far I can only do this using an extra variable as follows.

Class:

class Square
{
private:
    double length;

public:
    void setLength(double l);
    double getlength();
    double calcArea();
};

In main function:

Square s1;
double x;

cout << "Enter length: ";
cin >> x;

s1.setLength(x);

Thus, I use a temporary variable to pass user values to setters. My question is, is there a way to directly pass variables to the setter? or is there a better way?

Please note that I am a beginner in C++, therefor please be descriptive and simple. Thanks!!


Solution

  • You can either set the value using a variable or you can send a value, but the thing is that if you want to do it directly, it will break the law of Encapsulation. We can the class attributes private to make sure of Encapsulation. So for that, the thing you did is perfect ✌🏻.