Bernard Rosset
Bernard Rosset

Reputation: 4763

Reference in constructor parameter calls reference's default constructor

I am using the following classes declaration:

class A {
public:
    A(int, float);
    A(const A&);
};

class B {
public:
    B(A&);
protected:
    A a;
};

I also set up the following definition for B:

B::B(A &a) {
    this->a = a;
}

The problem is I have an error on the definition of my Bconstructor, telling me that there is No matching function for call to A::A().

Why does my B constructor tries to create a new A?

If the previous step is needed, why doesn't it call the copy constructor using the reference?

Upvotes: 0

Views: 210

Answers (1)

Doug T.
Doug T.

Reputation: 65649

I assume your B has an A that needs to be constructed. In your current constructor, your not explicitely specifying an A constructor to use. Therefore it tries the default constructor of A which does not exist:

Maybe you meant to construct B's A with the reference?

class B {
private:
    A _a;
public:
    B(A& a) : _a(a) {}

};

Upvotes: 3

Related Questions