0

Hi I am looking to initalize whole array to single element in constructor of class.I have tried this solution but I am getting this errror.

1>C:\Users\Ahmad Mustafa Anis\source\repos\ciruclar queue\Source.cpp(8,8): error C2590: 'sig': only a constructor can have a base/member initializer list
1>Done building project "ciruclar queue.vcxproj" -- FAILED.

My code is

class CircularQueue {
public:
    int dataItems[10];
    sig() : dataItems{0, 0, 0, 0, 0, 0, 0, 0, 0, 0} { }

};

I have Visual Studio 2019, I guess c++ version in it is cpp17. If there is someway I can add a constructor and assign whole array to 0 without for loop or explicitly element by element, like this constructor


CircularQueue() {
        dataItems = { 0 };
    }

or this one

CircularQueue() {
        dataItems =  0 ;
    }

In both case my error is

error C3863: array type 'int [10]' is not assignable

1
  • the method sig() is not a Constructor. You can only use initializer lists with Constructors. Commented Jun 13, 2020 at 12:05

1 Answer 1

2

If you want to initialize all values with 0

CircularQueue() : dataItems{} {}

Or,

CircularQueue() : dataItems{0,0,0,0,0,0,0,0,0,0} {}

If the array is too long, you can do this. It is not initializing. It's assigning after initialization.

CircularQueue() {
    std::fill(dataItems, dataItems+10, 3); //3 for example
}
Sign up to request clarification or add additional context in comments.

5 Comments

Its probably more safe to use dataItems+sizeof(dataItems).
@Flo No sizeof(dataItems) is 40.
This works. I need to assign 0 so the first technique is useful for me. Thanks.
@김선달 True, It would need to be divided by sizeof(int)
fill can use begin, end, so if the size is changed, it only needs to be done in one place.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.