Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Initializing array of Objects in C++ Composition

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  1. Why does this error occur ??
  2. When I comment the error code line and uncomment the non-error code line, it works fine. Why do we have to add the type wheel for the array definition?

>Solution :

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;
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading