I recently encountered this code in a past exam:
#include <iostream>
using namespace std;
class A
{
int x;
public:
A(int i):x(i) {}
int get_x() const
{
return x;
}
};
class B : public A
{
int *y;
public:
B(int i) :A(i)
{
y = new int[i];
for (int j = 0; j < i; j++)
y[j] = 1;
}
B(B&);
int &operator[](int i)
{
return y[i];
}
};
B::B(B& b)///no matching function for call to A::A()
{
y = new int[b.get_x()];
for (int i = 0; i < b.get_x(); i++)
y[i] = b[i];
}
ostream &operator<<(ostream& o, B a)
{
for (int i = 0; i < a.get_x(); i++)
o << a[i];
return o;
}
int main()
{
B b(5);
cout << b;
return 0;
}
It seems to me that when passing b
to operator<<
the compiler needs to make a copy of it, so it passes it to the copy constructor of B. But why would the copy constructor need A::A()
? Shouldn't it just use the default copy constructor in A and do a shallow copy of x
?