1

The following 3 code blocks are the main.cpp, static_class_array.cpp, and static_class_array.h respectively. I'm getting the following error:

static_class_array.cpp||In constructor 'static_array_class::static_array_class()':|
static_class_array.cpp|5|error: cannot convert '<brace-enclosed initializer list>' to 'int' in assignment|
||=== Build finished: 1 errors, 0 warnings ===|


#include "static_class_array.h"

int main()
{
    static_array_class* array_class;

    array_class = new static_array_class();

    delete array_class;

    return 0;
}


#include "static_class_array.h"

static_array_class::static_array_class()
{
    static_array_class::array[3] = {0,1,2};
}
static_array_class::~static_array_class(){}



#ifndef STATIC_CLASS_ARRAY_H
#define STATIC_CLASS_ARRAY_H

class static_array_class
{
    private:

        static int array[3];

    public:

    static_array_class();
    ~static_array_class();
};
#endif

2 Answers 2

2

I think that what you want in the implementation file is:

    static_array_class::static_array_class()
    {
    }
    static_array_class::~static_array_class(){}

    int static_array_class::array[3] = {0,1,2};

Explanation of error message

"cannot convert 'brace-enclosed initializer list' to 'int' in assignment"

in submitted code.

This is because the code:

static_array_class::array[3] = {0,1,2};

is interpreted as meaning that {0,1,2} should be assigned to element 3 in the array. Element 3 is of type int, (and incidentally not allocated being the fourth element), so this is like:

int i = 0;
i = {0,1,2};

Hence the error message.

Sign up to request clarification or add additional context in comments.

1 Comment

told me I had a conflicting declaration.
2

They are not the same type;

Your class is a class which includes a an array -- they other is just an array.

With a static definition of a class member you need to declare the actual instance outside the class, just like with any other static,

int static_array_class::array[3] = {0,1,2}; // note this line is outside the constructor

static_array_class::static_array_class()
{
}
static_array_class::~static_array_class(){}

4 Comments

Sure is possible with coding -- you just need a bit more -- static members of a class are initialized not in the constrictor but outside the class, since they are not actually part-taking in the constrction/deconstrction -- just can almost consider them just a part of the name space rather than the class.
I tried that and then it tells me \static_class_array\static_class_array.cpp|6|undefined reference to `static_array_class::array'|
Updated the answer, you need to move the initialization outside the constructor and declare the actual static member instance

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.