Static structure initialization with class elements

I have a structure that is defined with a lot of char* vanilla pointers, but also an object element. When I try to statically initialize such a structure, 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 an open default constructor with no arguments, so I did not 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 is the definition of SomeObject

 class SomeObject { void operator=(const SomeObject&); SomeObject(const SomeObject&); public: SomeObject() { // etc } // members snipped } 
+4
source share
3 answers

Initialization ex performs copy initialization. It takes a value on the right and uses it to initialize the variable on the left. For members of a class class, the corresponding constructor is used. In your case, this means calling the copy constructor for SomeObject , but you made this constructor private, so the compiler is right to tell you that SomeObject::SomeObject is a private member that cannot be accessed.

Although the compiler is allowed to call the copy constructor and initialize ex.obj directly using the default constructor, this is an optional optimization; it should still be allowed to invoke the copy constructor.

You can either provide example_struct your own constructor, or use it instead of initializing the bracket, or you can publish the SomeObject copy constructor.

+5
source

The rest of the members will be initialized to "0" rather than "default", right? Therefore, it is probably trying to call SomeObject(0) , which I think allows the creation of a private copy constructor.

+2
source

SomeObject constructor seems to be private.

+1
source

Source: https://habr.com/ru/post/1310171/


All Articles