Ocean11
Ocean11

Reputation: 45

What happen when we write empty copy constructor in derived class?

#include <iostream>
using namespace std;

class A {
    int i;
public:
    A(int );
};

A::A(int arg) {
    i = arg;
    cout << "A's Constructor called: Value of i: " << i << endl;
}

// Class B is derived from A
class B: A {
public:
    B(int );
    B(const B& ref)
    {
        cout<<"copy constructor get called"<<endl;
    }
};

B::B(int x):A(x) { //Initializer list must be used
    cout << "B's Constructor called";
}

int main() {
    B obj(10);
    return 0;
}
output:
prog.cpp: In copy constructor ‘B::B(const B&)’:
prog.cpp:20:2: error: no matching function for call to ‘A::A()’
  {
  ^
prog.cpp:10:1: note: candidate: A::A(int)
 A::A(int arg) {
 ^
prog.cpp:10:1: note:   candidate expects 1 argument, 0 provided

I got above error when I added copy constructor. When I remove copy constructor error is resolved. Can anybody explain me why I am getting error with copy constructor and even not creating object using copy constructor?

Upvotes: 0

Views: 182

Answers (2)

abhiarora
abhiarora

Reputation: 10430

You have defined an explicit empty copy constructor but it doesn't have any member initialization list.

By default, compiler will be calling A::A() in the member initialization list.

B(const B& ref): A()
{
    std::cout << "copy constructor get called" << std::endl;
}

Since, there is no default constructor of A which doesn't take any argument. The compiler is throwing an error:

error: no matching function for call to ‘A::A()’

Upvotes: 0

super
super

Reputation: 12928

Even if you don't use the copy constructor of B it still has to be valid.

Currently it does not invoke any constructor from A, so then it will default to contructing the base class with the default constructor.

Since there is no default constructor, you get an error.

Upvotes: 3

Related Questions