trikker
trikker

Reputation: 2709

Member initialization of a data structure's members

I just ran into an awkward issue that has an easy fix, but not one that I enjoy doing. In my class's constructor I'm initializing the data members of a data member. Here is some code:

class Button {
private:
    // The attributes of the button
    SDL_Rect box;

    // The part of the button sprite sheet that will be shown
    SDL_Rect* clip;

public:
    // Initialize the variables
    explicit Button(const int x, const int y, const int w, const int h)
        : box.x(x), box.y(y), box.w(w), box.h(h), clip(&clips[CLIP_MOUSEOUT]) {}

However, I get a compiler error saying:

C:\Users\Alex\C++\LearnSDL\mouseEvents.cpp|56|error: expected `(' before '.' token|

and

C:\Users\Alex\C++\LearnSDL\mouseEvents.cpp|56|error: expected `{' before '.' token|

Is there a problem with initializing member in this way and will I need to switch to assignment in the body of the constructor?

Upvotes: 2

Views: 1981

Answers (2)

Brian
Brian

Reputation: 31

The following is useful when St is not in your control and thus you cannot write a proper constructor.

struct St
{
    int x;
    int y;
};

const St init = {1, 2};

class C
{
public:
    C() : s(init) {}

    St s;
};

Upvotes: 3

Khaled Alshaya
Khaled Alshaya

Reputation: 96889

You can only call your member variables constructor in the initialization list. So, if SDL_Rect doesn't have a constructor that accepts x, y, w, h, you have to do it in the body of the constructor.

Upvotes: 5

Related Questions