Suppose I have a base class Person
and I publicly inherit a class Teacher
from base class Person
.
Now in the main function I write something like this
// name will be passed to the base class constructor and 17
// is for derived class constructor.
Teacher object(“name”,17) ;
Teacher object1=object; //call to copy constructor
Now I have not written the copy constructor for both the classes, off course the default copy constructors will be called. The Person class’s default copy constructor will first call the base class’s copy constructor.
Now the problem is suppose I write the copy constructor for the base class only, what happens is, the default copy constructor of the derived class will call my written copy constructor.
Now suppose I write the copy constructor for both the classes . now the copy constructor of the derived class (i.e Teacher) will call the default constructor of the base class but not the copy constructor why?
Is only default copy constructor of the derived class can call the copy constructor of the base class automatically?
You have to call the base copy constructor explicitly:
Teacher(const Teacher& other)
: Person(other) // <--- call Person's copy constructor.
, num_(other.num_)
{
}
Otherwise Person
's default constructor will be called.
All user defined constructors call their base's default constructor by default (unless they explicitly call a different constructor), it doesn't matter if the base's default constructor is user defined or compiler generated.
When a copy constructor is generated by the compiler it will call the base class's copy constructor.
Compiler defined constructors are not special, they can be called explicitly:
class Base {
int num_
public:
Base(int n) : num_(n) { }
// copy constructor defined by compiler
};
class Derived : public Base {
float flt_;
public:
Derived(float f, int n) : Base(n), flt_(f) { }
// Copy constructor
Derived(const Derived& other)
: Base(other) // OK to explicitly call compiler generated copy constructor
, flt_(other.flt_)
{
}
};
For more details see this Wikipedia article.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With