Sebastiaan van Dorst
Sebastiaan van Dorst

Reputation: 457

C++ structs defined in header and implemented in cpp

How can i make sure that the somecolor that i implement keeps his value when you use it in another class?

struct.h

struct Color{
   unsigned char r;
   unsigned char g;
   unsigned char b;
};
Color someColor;
//if i define the color here it says...:
Color someColor = {255,255,255}; //error: data member inializer not allowed

struct.cpp

struct::Color someColor = {255,255,255};

someotherclass.cpp

struct *str = new struct();
str->someColor.r //is not the correct value /not set

Upvotes: 4

Views: 23349

Answers (3)

Snail
Snail

Reputation: 49

You should write it like this:

struct.h

struct Color{
   unsigned char r;
   unsigned char g;
   unsigned char b;
};
extern Color someColor;

struct.cpp

#include "struct.h"    
Color someColor = {255,255,255};

someotherclass.cpp

#include "struct.h"
Color newColor;
newColor.r = someColor.r;

Upvotes: 4

Joseph Mansfield
Joseph Mansfield

Reputation: 110658

I'm going to rename your struct to mystruct for the sake of making it valid C++. It seems like you want to provide a default constructor for mystruct that initializes its someColor member to {255,255,255}. Pre-C++11, you would have to do that like this:

mystruct::mystruct()
{
  someColor.r = 255;
  someColor.g = 255;
  someColor.b = 255;
}

Alternatively, if you give Color a constructor that takes 3 values, you could do this:

mystruct::mystruct()
  : someColor(255, 255, 255)
{ }

However, in C++11 you can do aggregate initialization in the member initialization list, so you don't need to give mystruct a constructor:

mystruct::mystruct()
  : someColor{255, 255, 255}
{ }

In fact, in C++11 you're allowed to initialize non-static non-const members inside the class definition as you have attempted to do:

Color someColor = {255, 255, 255};

Upvotes: 4

You need to declare it in the header:

extern Color someColor;

and define it in the .cpp file:

Color someColor = {255, 255, 255};

Side note, your syntax struct::Color is highly misleading. It's parsed as struct ::Color, and in C++ terms, it's equivalent to ::Color or just Color (unless you're inside a namespace).

Upvotes: 6

Related Questions