Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object oriented programming , inheritance , copy constructors

Tags:

c++

oop

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?

like image 860
Zia ur Rahman Avatar asked Dec 29 '22 05:12

Zia ur Rahman


1 Answers

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.


I seem to not fully understand the question so I'll just say everything I think is relevant and hopefully this will help the OP.

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.

like image 152
Motti Avatar answered Feb 04 '23 02:02

Motti