Reputation: 109
I am trying a code which goes like this:-
class Something
{
private:
int data;
public:
Something(int data)
{
data = data;
}
int getdata()
{
return data;
}
};
int main()
{
Something xyz(5);
cout<<xyz.getdata()<<endl;
return 0;
}
The output of this is "0". i am stuck why this is coming as 0. kindly help. TIA.
Upvotes: 1
Views: 1298
Reputation: 2627
You can change the definition to
Something(int data):data(data)
{
}
and it will work, too. The parameter data
hides the field data
in the scope of the function. this->data
explicitly specifies the scope to be that of the class. I can't tell you why the above declaration works other than to say that the elements in the initialization list of the constructor must be fields of the class instance. So this may imply the scope. While the values with which they are initialized come from the function scope.
Upvotes: 3