Forgetting something about member initializer lists

Hi, I have a simple coord class, representing coordinates, and a simple window class, representing a window, here is my code right now.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//Coord.h
struct Coord
{
private:
    int m_x,m_y;
public:
    Coord(int x, int y) : m_x(x),m_y(y) {}
};

//Window.h
class Window
{
    int width;
    int height;
    Coord top_left;
public:
    Window(Coord tl, int h, int w) : top_left{tl},height{h},width{w} {}
};

If I were to make a default constructor, it would be this:
 
Window() : top_left{/*???*/} , height{0},width{0} {}

Right now, the only way I can think of initializing top_left is like this in the body of the constructor:
1
2
3
4
{
    Coord tt{0,0};
    top_left = tt;
}

But this seems rather stand-out and messy. Is their anyway I could achieve the same using a member initializer list in any way I keep thinking that I am overthinking this and their is a simple solution. Is there?
Last edited on
Two immediate options:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Window
{
    Coord top_left;
public:
    Window()
    : top_left{0,0} // a constructor call
    {}
};

class Window
{
    Coord top_left {0,0}; // default initializers can be written into declarations
public:
    Window()
    {}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
struct Coord
{
    private:
        int m_x,m_y;
    public:
        Coord(int x, int y) : m_x(x),m_y(y) {}
};

class Window_a
{
    int width = 0 ;
    int height = 0 ;
    Coord top_left{ 0, 0 };

    public:
        Window_a() = default ; // explicitly defaulted constructor
        Window_a( Coord tl, int h, int w ) : width{w}, height{h}, top_left{tl} {}
};

class Window_b
{
    int width ;
    int height ;
    Coord top_left ;

    public:
        Window_b() : Window_b( {0,0}, 0, 0 ) {} ; // delegating constructor
        Window_b( Coord tl, int h, int w ) : width{w}, height{h}, top_left{tl} {}
};

class Window_c
{
    int width ;
    int height ;
    Coord top_left ;

    public:
        Window_c() : width{0}, height{0}, top_left{0,0} {} ; // member initialiser list
        Window_c( Coord tl, int h, int w ) : width{w}, height{h}, top_left{tl} {}
};
Topic archived. No new replies allowed.