0

In the below code I have defined an explicit copy constructor in the derived class. I have also written my own copy constructor in the base class.

Primer says that the derived copy constructor must call the base one explicitly and that inherited members should be copied by the base class copy constructor only, but I copied the inherited members in the derived class copy constructor and it is working fine. How is this possible?

Also how do I explicitly call the base class copy constructor inside the derived class copy constructor? Primer says base(object), but I am confused how the syntax differentiates between normal constructor call and copy constructor call.

Thanks in advance.

#include<stdafx.h>
#include<iostream>

using namespace std;

class A
{
public:
  int a;
  A()
  {
    a = 7;
  }

  A(int m): a(m)
  {
  }
};

class B : public A
{
public:
  int b;
  B()
  {
    b = 9;
  }

  B(int m, int n): A(m), b(n)
  {
  }

  B(B& x)
  {
    a = x.a;
    b = x.b;
  }

  void show()
  {
    cout << a << "\t" << b << endl;
  }
};

int main()
{
  B x;
  x = B(50, 100);
  B y(x);
  y.show();
  return 0;
}
user657267
  • 20,568
  • 5
  • 58
  • 77
  • Please use punctuation, and don't use tabs to indent your code. – user657267 Oct 24 '14 at 06:09
  • You did not define a copy constructor in `A` (there is an implicitly-generated one). You do not have to explicitly call `A`'s copy constructor from `B`'s. Your code invokes `A`'s copy constructor and then you overwrite the values, which is fine. – M.M Oct 24 '14 at 06:28

2 Answers2

1

copy constructor is when you have another Object passed to your constructor:

class A() {
    private:
        int a;
    public:
        //this is an empty constructor (or default constructor)
        A() : a(0) {};
        //this is a constructor with parameters
        A(const int& anotherInt) : a(anotherInt) {};
        //this is a copy constructor
        A(const A& anotherObj) : a(anotherObj.a) {}; 
}

for a derived class

class B : public A {
    private:
         int b;
    public:
         //this is the default constructor
         B() : A(), b() {};
         //equivalent to this one
         B() {};
         //this is a constructor with parameters
         // note that A is initialized through the class A.
         B(const int& pa, const int& pb) : A(pa), b(pb) {}
         //for the copy constructor
         B(const B& ob) : A(ob), b(ob.b) {}        
}
Marco Aurelio
  • 20,724
  • 1
  • 17
  • 16
0

How somebody else wrote here:

How to call base class copy constructor from a derived class copy constructor?

I would write the copy constructor like this instead how it was written by macmac:

B(const B& x) : A(x) , b(x.b)
{
}

To call the copy constructor of the base A you simply call it passing the derived B object A(B), is not neccessary to specify B.a.

EDIT: macmac edited his answere in the correct way, now his answere is better then mine.

Community
  • 1
  • 1
IFeelGood
  • 397
  • 1
  • 12