Thoughts on default constructor ?

closed account (o1vk4iN6)
Should the default constructor on a data type, such as 3d point, be left alone?

I've recently come across a library I use and such a situation presented itself where I needed a constructor which would not modify the data. Luckily the library is open sourced so I was able to change the default constructor from initializing to zero.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

class point3
{
public:

     float x, y, z;

     point3() 
          : point3(0) // yeh or neh
     {
     }

     point3(float c) : x(c), y(c), z(c)
     {
     }

};


So now say we have the following constructor instead. Would the following work as intended to provide a choice as with Plain Old Data ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

class point3
{
public:
     float x, y, z;

     point3()
     {
     }

     point3(float c = 0.f) : x(c), y(c), z()
     {
     }

};


point3 *pt1 = new point3;    // default construct
point3 *pt2 = new point3(); // point(0.f)


Last edited on
closed account (zb0S216C)
xerzi wrote:
"Should the default constructor on a data type, such as 3d point, be left alone?"

If a class consists of primitive types, such as int and float, then the compiler can easily initialise them without explicit instructions from the programmer. However, if you plan on doing something the compiler will not do, then why not.

xerzi wrote:
"So now say we have the following constructor instead. Would the following work as intended to provide a choice as with Plain Old Data ?"

The two constructors the same, which is ambiguous. And no, it's won't work as a POD type unless you're following C++11.

Since point3::z isn't given a proper value at the point of its initialisation, it's a good enough reason to overload the trivial constructor, because the non-trivial constructor's behaviour is different than the trivial default constructor.

Wazzak
Last edited on
> Should the default constructor on a data type, such as 3d point, be left alone?

Depends on whether the type-invariant is trivial or not - if it is trivial, the default constructor can be trivial.

1
2
3
4
5
6
7
8
9
10
struct point3 // trivial class invariant
{
    double x, y, z ; // public; no invariant to maintain

    point3() = default ; // trivial default constructor

    explicit point3( double f ) { x = y = z = f ; }

    // ...
};


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct wall_clock // non-trivial class invariant
{
    bool valid() const // invariant: must return true
    { return hour>=0 && hour<24 && minute>=0 && minute<60 ; }

    wall_clock() : hour(0), minute(0) { assert( valid() ) ; } // establish invariant

    explicit wall_clock( int hr, int min ) : hour(hr), minute(min)
    { assert( valid() ) ; } // assert invariant

    // ...

    private:
        int hour, minute ; // private; invariant must be maintained
};
Topic archived. No new replies allowed.