Reputation: 27
Here is the code:
#include<iostream>
using namespace std;
class Rectangle
{
private :
int _width;
int _height;
public :
Rectangle()
: _width{},_height{}
{}
Rectangle(int initial_w, int initial_h)
: _width{initial_w}, _height{initial_h}
{}
int get_width(){return _width;}
};
int main()
{
Rectangle a;
Rectangle(2,3);
cout<<a.get_width()<<endl;
}
I don't understand why it returns 0, i thought it is supposed to be 2. Please help!!!!!
Upvotes: 2
Views: 91
Reputation: 7895
Let's Look at your code within main()
line by line:
Rectangle a; Rectangle(2,3); cout<<a.get_width()<<endl;
In the first line, you are creating an instance of a Rectangle Object and it is using the default constructor which can in truth be any value as the member variables are not initialized to 0 directly or some other value.
In your second line of code, you are using the classes constructor without declaring it as a variable object while not assigning it to any previously existing variable instance which in turn creates a temporary that will be constructed and destroyed before you even call std::cout
.
In your third statement, you are using your class's get_width()
message which is returning exactly what the default constructor initialized the member variable to when you declared the variable a
.
There are a few ways to fix this:
Rectangle a(2,3);
std::cout << a.get_width() << '\n';
Rectangle b = Rectangle(4,5);
std::cout << b.get_width() << '\n';
The first line uses the user-defined constructor which is preferred in many cases. The second line requires the use of the copy constructor and assignment operator, here it's fairly trivial so, the default versions of these are used. However, in more complex classes and classes that will use the heap and dynamic memory will require the use of the copy constructor and assignment operator to be user-defined.
Upvotes: 2
Reputation: 359
In your main method, you create a Rectangle a;
, which calls your default constructor Rectangle()
. Then in the next line you create a temporary element with Rectangle(2,3);
, which calls your initialization constructor Rectangle(int initial_w, int initial_h)
, but it is discarded immediately, as you have not assigned it to a variable. Finally, you output your default-constructed variable a.
It seems what you want to achieve is this:
int main()
{
Rectangle a(2, 3);
cout << a.get_width() << endl;
}
Upvotes: 7