Search code examples
c++constructorassignment-operatorcopying

default constructors and object copying


I'm wondering why I need to declare a default constructor in this case. For one thing doesn't the compiler do that automatically if i leave it out? And regardless, I still don't see why its necessary. Also, I get the error even if I omit 'obj_B = origin.obj_B;'

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;}; //error:no matching function for call 
                                                      //to B::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;
}

Solution

  • The compiler only creates a default constructor if you don't specify an alternate constructor.

    Because you made:

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

    The default constructor will not be created for you.

    The specific error you're getting is because A(A const &origin) doesn't specify the constructor to use for obj_B explicitly.

    The following code would work:

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

    By the way, you don't need a trailing semicolon on a function definition.