I have a struct that’s defined with a large number of vanilla char* pointers, but also an object member. When I try to statically initialize such a struct, I get a compiler error.
typedef struct
{
const char* pszA;
// ... snip ...
const char* pszZ;
SomeObject obj;
} example_struct;
// I only want to assign the first few members, the rest should be default
example_struct ex = { "a", "b" };
SomeObject has a public default constructor with no arguments, so I didn’t think this would be a problem. But when I try to compile this (using VS), I get the following error:
error C2248: 'SomeObject::SomeObject' : cannot access private member declared in class 'SomeObject'
Any idea why?
Update: Here’s the definition of SomeObject
class SomeObject
{
void operator=(const SomeObject&);
SomeObject(const SomeObject&);
public:
SomeObject()
{
// etc
}
// members snipped
}
Your initialization of
experforms copy-initialization. It takes the value on the right and uses it to initialize the variable on the left. For class-type members, the appropriate constructor is used. In your case, that means invoking the copy constructor forSomeObject, but you’ve made that constructor private, so the compiler is correct in telling you thatSomeObject::SomeObjectis a private member that can’t be accessed.Although the compiler is allowed to elide the call to the copy constructor and initialize
ex.objdirectly with the default constructor, that is an optional optimization; it still needs to be allowed to call the copy constructor.You can either give
example_structa constructor of your own and use that in place of brace initialization, or you can publicizeSomeObject‘s copy constructor.