I have a vector of A objects. class A contains a member object of type B. class B contains a statically declared array of bool. When I copy an A object into the vector, the values in the bool array are lost. I though this shouldn't be a problem because the array of bool is statically declared. Do I need to handle this using a copy constructor?

class B
{
public:
    bool theArray[5] ;

    B(bool x) {theArray[1] = x;};
    B(){};

};

class A
{
public:
    B obj_B;

    A() : obj_B(1) {};
    A(A const &origin) : obj_B(origin.obj_B){};
};

int main () 
{
    std::vector <A> someAs;
    for(int q=0;q<10;q++)
        someAs.push_back(A());

    for(int q=0;q<10;q++)
        std::cout << someAs[q].obj_B.theArray[1] << std::endl;
}
1

There are 1 best solutions below

2
On BEST ANSWER

You shouldn't need to define a copy constructor to do this. I'm not sure what you mean by "static arrays," since there are two meanings, but neither require a copy constructor.

If you mean "array that's statically sized," like this:

class MyClass {
private:
    bool myArray[137];
};

Then the default copy constructor will do a memberwise copy of the elements from the object being copied.

If you mean "a static array of bools," like this:

class MyClass {
private:
    static bool myArray[137];
};

Then the copy constructor won't touch this array because it's shared across all instances of the class.

If your array of bools is getting corrupted, you might have a memory corruption bug on your hands, perhaps by reading off the end of an array or dereferencing a bad pointer. I'd look into this, since the default copy behavior will indeed give you what you want.