简体   繁体   中英

Copy contructor c++ with base and derive class

I have two derived classes( Student and Teacher ) who inherit from base class People . When I want to declare 2 variable st , tc with type pointer to People , but pointing to objects of Student and Teacher types to add into this linked-link:

class Node
{
private:
    People* data;
    Node* next;
};

so I write:

People * st = new Student(...);
People * tc = new Teacher(...);

Now I want to write a copy contructor to clone st , tc (like People *st1 = st or everything else to clone those variales without using default code) so how can I do it? Thank you! p/s: sorry for my bad english.

You can write a copy constructor that does the following:

People p(*st);

The type of p will be People and not Student though. If you want to create a Student then you can add a virtual function to People called clone as follows:

class People {
...

  virtual People *clone() = 0;
}

And then in each derived class implement it to return an instance of the derived type. This way your usage would be:

People *st = new Student();
People *stClone = st->clone();

Here the type of stClone is Student and not People .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM