2

I'm just supposed to be getting used to basic copy constructors.

I assumed I properly placed copy constructors.

But when I try to compile, I keep getting the error "No matching constructor for initialization of B"

I'm a bit confused.

class A {
    int valuea;

public:     
    A(const A&); // copy constructor
    int getValuea() const { return valuea; }
    void setValuea(int x) { valuea = x; }
};

class B : public A {
    int valueb;
public:
    B(int valueb);
    B(const B&); // copy constructor
    int getValueb() const { return valueb; }
    void setValueb(int x) { valueb = x; }
};

int main () {
    B b1;
    b1.setValuea(5);
    b1.setValueb(10);
    B b2(b1);
    cout << "b2.valuea="  << b2.getValuea() << "b2.valueb="  << b2.getValueb() << endl;

    return 0;
}
slacy
  • 11,397
  • 8
  • 56
  • 61
user1751669
  • 21
  • 1
  • 2
  • 2
    You have no default constructor for either A or B - as soon as you declare a constructor - the compiler will not generate the default constructors. – Adrian Cornish Oct 17 '12 at 00:31
  • The `B(int)` constructor can act as a default constructor for `B` if you give the `valueb` parameter a default value, thus allowing the `B b1;` statement to work. However, `A` has no constructor that `B`'s constructor can call, so `B` still cannot be constructed at all. – Remy Lebeau Jun 08 '13 at 01:01

1 Answers1

4

By declaring B(int) and B(const B &), you have disabled the default constructor that is implicitly placed in the class for you when you have no other constructors because for all the compiler knows, you might not want a default constructor, so it can't make assumptions (see here).

Add the following to B, remembering to initialize the base and members with it:

B(){}

In C++11, this works well:

B() = default;

That will allow B to have a default constructor for use when you declare B b1;

The same thing goes for A, too. You have a copy constructor, so there's no longer any default constructor implicitly placed in for you.

Community
  • 1
  • 1
chris
  • 60,560
  • 13
  • 143
  • 205