views:

299

answers:

1

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?

+5  A: 

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.

AraK
or write a helper function which takes those 4 parameters and returns a `SDL_Rect`. Then you can call that in the initializer list.
jalf