What you are doing there is assignment, not initialization. Initialization happens in the initialization list of a constructor, before the constructor body, or in C++11 in an initializer right after the member variable declaration:
myClass.hpp, general case:
/** you might want to do this if you are linking
* against the C lib or object file of that header:
*/
extern "C" {
#include fileWithStruct.h
}
class myClass
{
public:
foo bar; //no need for "struct" in C++ here
};
C++11:
myClass.cpp
#include "myClass.hpp"
//Initialize structure in Constrcutor
myClass::myClass( )
: bar{1, 0, "someString", 0x4}
{}
Antoher option is to provide the initial value of foo with an brace-or-equal-initializer at the member variable declaration:
myClass.hpp
extern "C" {
#include fileWithStruct.h
}
class myClass
{
public:
foo bar{1, 0, "someString", 0x4};
};
In this case, you need not define a constructor, since it's generated implicitly by the compiler (if needed), correctly initializing bar
.
C++03:
Here aggregate initialization in init lists is not available, so you have to use workarounds, e.g.:
myClass.cpp
#include "myClass.hpp"
//Initialize structure in Constrcutor
myClass::myClass( )
: bar() //initialization with 0
{
const static foo barInit = {1, 0, "someString", 0x4}; //assignment
bar = barInit;
}
Or:
#include "myClass.hpp"
namespace {
foo const& initFoo() {
const static foo f = {1, 0, "someString", 0x4};
return f;
}
}
//Initialize structure in Constrcutor
myClass::myClass( )
: bar(initFoo()) //initialization
{ }