Woody20
Woody20

Reputation: 867

Initialize a static member of a class that includes an array?

I have a C++ class with a static data member which is a constant. I added an array to the class definition, and now I get an error when trying to initialize the static member.

Here is the code:

class MyClass
{

int i1;
int i2;
int i3;
//bool b1[2];
//bool b2[2];

public:
    //Constructors
    MyClass();
    MyClass(const int i1In, const int i2In, const int i3In
        /*, const bool b1In[2], const bool b2In[2]*/
        );
// Copy constructor
MyClass(const Input& rhs);

// Destructor
~MyClass();

// Assignment
MyClass& operator=(const MyClass& rhs);

// Operators
bool operator==(const MyClass& m2) const;
bool operator!=(const MyClass& m2) const;
MyClass& operator++(int/*serves no purpose, but must be included*/);

static const MyClass S;
};

const MyClass S = { 0, 0, 0 /*,{ false,false }, { false,false }*/ };

The above code compiles without error, and the value of S is as expected. However, when I change the class definition to add the arrays b1 and b2 (uncomment two places in the class defn and add two array initializers in the initialization of S), I get the error

"C2440: 'initializing': cannot convert from 'initializer list' to 'MyClass' note: No constructor could take the source type, or constructor overload resolution was ambiguous".

What is the proper way to define a constant variable of type MyClass that has the indicated values?

Windows 7 Pro, Visual Studio 2015

Upvotes: 1

Views: 96

Answers (1)

Weak to Enuma Elish
Weak to Enuma Elish

Reputation: 4637

Have the constructor take the array parameters by constant reference.

MyClass(/*...*/ const bool (&b1In)[2], const bool (&b2In)[2])

const MyClass MyClass::S(/*...*/ { false,false }, { false,false } );

The array-as-parameter syntax is really just a cleverly disguised pointer which is why that didn't work.

Also, your operator++(int) returns a reference. Because that is the post-increment operator, it should return by value.

Upvotes: 1

Related Questions