I am trying to create a very basic class with the default contructor:
class Point {
public:
Point() = default;//con 1
explicit Point(double x): x_axis(x), y_axis(0){}//con 2
Point(const Point &other) = default;
~Point() = default;
private:
double x_axis;
double y_axis;
}
But when I try to use the default contructor in the main functtion it generates a random juck value for x_axis:
Point p1;//generates random value
Point p2{};//works as intended
so my question is, why is that? when I do the other contructor (con 2) like so:
explicit Point(double x = 0): x_axis(x), y_axis(0){}
both of them work as intended. so technically I have 2 questions,
- why in the first try, no brackets generated a random value but {} worked, and in the second try they both worked
- what even is calling the default constructor with {}?
CodePudding user response:
It's because the second constructor initializes the member variables with values while the first constructor leaves the member variables with indeterminate values.
Either do:
class Point {
public:
Point() : x_axis{}, y_axis{} {} // instead of = default
...
or
class Point {
public:
Point() = default;
// ...
private:
double x_axis{}; // {} or
double y_axis = 0.0; // = 0.0
};
CodePudding user response:
why in the first try, no brackets generated a random value but {} worked, and in the second try they both worked
In the first try when you wrote:
Point p1; //this uses default constructor
Here the default ctor is used which just default initializes the data members y_axis
and y_axis
. Since these are built in types, they have indeterminate values.
In the second try when you wrote:
Point p2{}; //this is zero initailization
The above is zero initialization meaning the each data members is initialized to 0
.
Now, when you provided the following constructor:
explicit Point(double x = 0): x_axis(x), y_axis(0) //this is a default constructor
{
}
The above is a default constructor that initializes both the data members with 0
in the constructor initializer list.
Thus, this time when you write:
Point p1; //this uses the above provided default ctor
This time p1
is default constructed using the default ctor that initializes both the data members to 0
and hence both x_axis
and y_axis
of p1
will be initialized to 0
.