Home > Net >  Problem with a junk value in a member when using an empty default constructor
Problem with a junk value in a member when using an empty default constructor

Time:05-16

I am trying to create a very basic class with a default constructor:

    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;
    }

When I try to use the default constructor in the main() function, it generates a random junk value for x_axis:

    Point p1;//generates random value
    Point p2{};//works as intended

Why is that? When I use the other constructor (con 2) like so:

    explicit Point(double x = 0): x_axis(x), y_axis(0){}

Both of them work as intended.

  1. why, in the first try with no brackets, does it generate a random value, but {} worked, but in the second try they both work?
  2. what 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.

  • Related