Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static initialization of a struct with class members

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
}
like image 934
JSBձոգչ Avatar asked Feb 27 '23 00:02

JSBձոգչ


1 Answers

Your initialization of ex performs 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 for SomeObject, but you've made that constructor private, so the compiler is correct in telling you that SomeObject::SomeObject is a private member that can't be accessed.

Although the compiler is allowed to elide the call to the copy constructor and initialize ex.obj directly 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_struct a constructor of your own and use that in place of brace initialization, or you can publicize SomeObject's copy constructor.

like image 92
Rob Kennedy Avatar answered Mar 11 '23 15:03

Rob Kennedy