0

I'm trying to do deep cloning in inherited relationship, where MyFriendInfo is a base class and MyFriendDetailInfo is a derived class. I could easily do deep cloning if it's not in inherited relation. But in this case, should I put "copying creator" (I don't exactly know in English) to both base class, which is "MyFriendInfo(const MyFriendInfo &copy)" and derived class, which is "MyFriendDetailInfo(const MyFriendDetailInfo &copy)", like I did? or what else can I do for deep cloning?

#include <iostream>
#include <cstring>
using namespace std;

class MyFriendInfo
{
private:
    char *name;
    int age;
public:
    MyFriendInfo(char *xname, int xage) : age(xage)
    {
        name=new char[strlen(xname)+1];
        strcpy(name, xname);
    }
    MyFriendInfo(const MyFriendInfo &copy) : age(copy.age)
    {
        name=new char[strlen(copy.name)+1];
        strcpy(name, copy.name);
    }
    void ShowMyFriendInfo()
    {
        cout<<"Name: "<<name<<endl;
        cout<<"Age: "<<age<<endl;
    }
    ~MyFriendInfo()
    {
        delete []name;
    }
};

class MyFriendDetailInfo : public MyFriendInfo
{
private:
    char *addr;
    char *phone;
public:
    MyFriendDetailInfo(char *xaddr, char *xphone, char *xname, int xage) 
                        : MyFriendInfo(xname, xage)
    {
        addr=new char[strlen(xaddr)+1];
        strcpy(addr, xaddr);
        phone=new char[strlen(xphone)+1];
        strcpy(phone, xphone);
    }
    void ChangePhone(char *cphone)
    {
        strcpy(phone, cphone);
    }
    MyFriendDetailInfo(const MyFriendDetailInfo &copy) 
        : MyFriendInfo(const MyFriendInfo &copy) 
    {
        addr=new char[strlen(copy.addr)+1];
        strcpy(addr, copy.addr);
        phone=new char[strlen(copy.phone)+1];
        strcpy(phone, copy.phone);
    }  
    void ShowMyFriendDetailInfo()
    {
        ShowMyFriendInfo();
        cout<<"Address: "<<addr<<endl;
        cout<<"Phone Num: "<<phone<<endl;
    }
    ~MyFriendDetailInfo()
    {
        delete []addr;
        delete []phone;
    }
 }; 
pkc1088
  • 9
  • 4
  • The duplicate is a bit old, a `clone()` function should return `std::unique_ptr` instead of `T*`. But otherwise the principal is correct. – François Andrieux Oct 27 '21 at 01:50
  • Your classes do not implement the [rule of 3/5/0](https://en.cppreference.com/w/cpp/language/rule_of_three) correctly. You also need to implement `operator=`. – François Andrieux Oct 27 '21 at 01:51
  • I haven't studied virtual class or templates stuff yet then would it be better to consider my question later after I study all of them? – pkc1088 Oct 27 '21 at 01:58

0 Answers0