Initializing members of data structure members

I just ran into an awkward problem that has an easy fix, but not something I like to do. In my class constructor, I initialize the data members of the data member. Here's 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 am getting a compiler error:

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 initializing an element this way and I need to switch to assignment in the constructor body?

+2


source to share


2 answers


You can only call your member variable constructor in initialization list

. So, if it SDL_Rect

doesn't have constructor

which accepts x, y, w, h

, you must do it in the body of the constructor.



+5




In case St is not under your control and therefore you cannot write the correct constructor.



struct St
{
    int x;
    int y;
};

const St init = {1, 2};

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

    St s;
};

      

+3


source







All Articles