Search code examples
c++compiler-errorsstatic-variables

C++ in-class initialization of static data member


I am trying to make a class for these two variables(window, windowSurface) so I can access them in different areas of my code. My error is:

include/windowSurface.h|11|error: field initializer is not constant|
include/windowSurface.h|11|error: in-class initialization of static data member ‘SDL_Window windowSurface::window’ of incomplete type

From the Code Below

#ifndef WINDOWSURFACE_H
#define WINDOWSURFACE_H
#include "SDL2/SDL.h"

class windowSurface
{
    public:
        windowSurface();
        virtual ~windowSurface();
        static SDL_Window window = SDL_CreateWindow( "Tetris", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_SHOWN );
        static SDL_Surface windowSurface = SDL_GetWindowSurface( window );
    protected:
    private:
};

#endif // WINDOWSURFACE_H

What am I doing wrong and how do I fix this?


Solution

  • Read carefully errors that compiler gives you.

    Static data members can be declared, but not defined within class definition, unless this static data member of integral or enumeration type and is declared const (and not volatile).

    Since C++11 static data member of LiteralType and declared as constexpr can be initialized with a brace-or-equal initializer that is a constant expression inside the class definition.

    Also it's bad idea to give a static member name that match with its class name.

    Remove initialization of static members and rename windowSurface to surface:

    class windowSurface
    {
    public:
        windowSurface();
        virtual ~windowSurface();
        static SDL_Window window;
        static SDL_Surface surface;
    protected:
    private:
    };
    

    and add a definition in corresponding cpp file:

    SDL_Window windowSurface::window = SDL_CreateWindow( "Tetris", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_SHOWN );
    SDL_Surface windowSurface::surface = SDL_GetWindowSurface( windowSurface::window );