0

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?

Jake Wright
  • 373
  • 1
  • 8
  • @DanielLangr so if I understand correctly: if the CC in the derived class doesn't explicitly call the CC for the base class, then it calls the constructor with no arguments of the base class by default – Jake Wright Jun 04 '20 at 08:34
  • Yes. I believe the reason for this rule is the consistency across all manually-written constructors, such that they initialize subobjects in the same way. – Daniel Langr Jun 04 '20 at 08:39

0 Answers0