I have a basic C++ class .The header looks like this:
#pragma once
class DataContainer
{
public:
DataContainer(void);
~DataContainer(void);
int* getAgeGroup(void);
int _ageGroupArray[5];
private:
int _ageIndex;
};
Now inside the cpp file of the class I want to intialize the _ageGroupArray[5] with default values inside the class contructor like this:
#include "DataContainer.h"
DataContainer::DataContainer(void)
{
_ageGroupArray={20,32,56,43,72};
_ageIndex=10;
}
int* DataContainer::getAgeGroup(void){
return _ageGroupArray;
}
DataContainer::~DataContainer(void)
{
}
Doing it I am getting "Expression must be a modifiable lvalue" on _ageGroupArray line.So is it entirely impossible to initialize an array object in the constructor? The only solution I found was to define the array outside scope identifiers .Any clarification on this will be greatly appreciated.
To resolve this error you need to ensure you do not assign Z variable to an expression X + Y like so (X + Y = Z). Instead, use the comparison operator (==). This simple modification of the code will solve this conditional statement error.
A modifiable lvalue is addressable (can be the operand of unary &) and assignable (can be the left operand of =). A non-modifiable lvalue is addressable, but not assignable. An rvalue is neither addressable nor assignable.
For example, a const object is an lvalue that cannot be modified. The term modifiable lvalue is used to emphasize that the lvalue allows the designated object to be changed as well as examined. Lvalues of the following object types are not modifiable lvalues: An array type.
But, the elements in an array can be explicitly initialized to specific values when it is declared, by enclosing those initial values in braces {}. For example: int foo [5] = { 16, 2, 77, 40, 12071 };
In the current standard, as you have already noticed, you cannot initialize a member array in the constructor with the initializer list syntax. There are some workarounds, but none of them is really pretty:
// define as a (private) static const in the class
const int DataContainer::_age_array_size = 5;
DataContainer::DataContainer() : _ageIndex(10) {
int tmp[_age_array_size] = {20,32,56,43,72};
std::copy( tmp, tmp+_age_array_size, _ageGroupArray );
}
If the values in the array are always the same (for all object in the class) then you can create a single static copy of it:
class DataContainer {
static const int _ageGroupArraySize = 5;
static const int _ageGroupArray[ _ageGroupArraySize ];
// ...
};
// Inside the cpp file:
const int DataContainer::_ageGroupArray[_ageGroupArraySize] = {20,32,56,43,72};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With