user2621476
user2621476

Reputation: 91

output of program is not same as passed argument

Why I am getting different out put of both the width and height variable in below program

#include <iostream>

using namespace std;

class my_space {
    public :
        void set_data(int width,int height) // taking the same name of the variable as the class member functions
        {
            width = width;
            height = height;
        }
        int get_width()
        {
            return width;
        }
        int get_height()
        {
            return height;
        }
    private : 
        int width;
        int height;
};


int main() {
    my_space m;
    m.set_data(4,5); // setting the name of private members of the class
    cout<<m.get_width()<<endl;
    cout<<m.get_height()<<endl;
    return 0;
}

getting below output of the program

sh-4.3$ main                                                                                                                                                        
1544825248                                                                                                                                                          
32765

Upvotes: 2

Views: 50

Answers (1)

NathanOliver
NathanOliver

Reputation: 180630

The problem here is that int width and int height in function parameter list hide the width and height class member variables since the have the same name. What your function does is assign the passed in values to themselves and then exist. This means the width and height in the class are left uninitialized and they hold some unknown value. What you need to do if you want the names to be the same is use the this pointer to diferentiate the names like

void set_data(int width,int height) // taking the same name of the variable as the class member functions
{
    this->width = width;
    this->height = height;
}

Now the compiler knows which is which. You could also just name the function parameters to something else and then you would not need to use this->.

Also instead of having a set function you could use a constructor and initialize the object when you create it. A constructor like

my_space(int width = 0, int height = 0) : width(width), height(height) {}

Here we can use the same names as the compiler knows which one is the member and which one is the parameter

Will always make sure the class is at least default constructed to a known state or you can provide your own values to make it a non-default state.

Upvotes: 11

Related Questions