Matt Munson
Matt Munson

Reputation: 3003

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;
}

Upvotes: 0

Views: 187

Answers (4)

Lou
Lou

Reputation: 1955

To make one final point...

Assuming you hadn't defined a non-default constructor, failing to define a default constructor would've resulted in the elements of theArray[] being undefined. That is a bad habit to get into usually leading to bugs down the road.

Upvotes: 0

aschepler
aschepler

Reputation: 72271

To define a copy constructor for A that does not require a default constructor for B, use member initializer syntax:

class A {
public:
    A(A const& origin) : obj_B(origin.obj_B) {}
    //...
};

Upvotes: 2

Wheatevo
Wheatevo

Reputation: 643

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.

Upvotes: 6

Jerry Coffin
Jerry Coffin

Reputation: 490058

If you don't define any ctors for a class, the compiler will synthesize a default constructor. If you define another constructor though (e.g., one that takes an argument) then the compiler does not synthesize one for you, and you have to define one yourself.

In case you care, C++ 0x adds an "=default;" declaration to tell the compiler to provide a ctor that it would have provided by default, even if you have defined another ctor.

Upvotes: 2

Related Questions