I wanted to design a composition
using C
as shown below:
#define NUMBER (4)
class wheel {
int radius;
public:
wheel();
wheel(int);
//copy constructors prototype
//getters and setters prototypes
};
wheel::wheel() : radius(1) {}
wheel::wheel(int r) : radius(r) {}
//wheel class copy constructor definition
//wheel class setter and getter definitions
class car {
wheel fourwheels[NUMBER];
public:
car();
};
car::car() {
fourwheels[NUMBER] = {wheel(1), wheel(1), wheel(1), wheel(1)}; //error code
//wheel fourwheels[NUMBER] = {wheel(1), wheel(1), wheel(1), wheel(1)}; //non-error code
}
int main() {
car mycar;
return 0;
}
While compiling the code, I am getting the following error:
error: no match for 'operator=' (operand types are 'wheel' and '<brace-enclosed initializer list>')
Queries:
- Why does this error occur ??
- When I comment the
error code
line and uncomment thenon-error code
line, it works fine. Why do we have to add the typewheel
for the array definition?
CodePudding user response:
You are attempting to assign to an array element. And one that's out of range at that.
Using the constructor's initializer list, this will compile, though you should consider using STL containers rather than a raw array.
car::car() : fourwheels{wheel(1), wheel(1), wheel(1), wheel(1)}
{
}
The code you had commented out "worked" because it declared and initialized a new array of four wheels.
Since the default constructor for wheel
provides a radius of 1
, you could also write:
car::car() : fourwheels{wheel(), wheel(), wheel(), wheel()}
{
}
But, if we used std::array
to hold our wheels, we can simplify this further, as the elements of fourwheels
will be initialized using the wheel
type's default constructor, which we don't have to write.
class car {
std::array<wheel, NUMBER> fourwheels;
};
CodePudding user response:
Why does this error occur ??
Raw arrays are not copy-assignable. That is, the following will not work:
int nums[4] = {};
nums = {1, 2, 3, 4};
That is essentially what you're trying to do in your car
constructor. Instead, you need to initialize the fourwheels
member in the member initialization list:
car::car()
: fourwheels{wheel(1), wheel(1), wheel(1), wheel(1)}
{}
When I comment the
error code
line and uncomment thenon-error code
line, it works fine. Why do we have to add the typewheel
for the array definition ??
Because you're not initializing your car
class's member there. You're declaring and initializing a different array, also named fourwheels
that is local to the constructor body. The class member remains default-initialized.