Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep copy dynamically allocated object in C++

Hello guys I couldn't find a way build up a proper copy constructor for a dynamically allocated object. It yells that: error: no matching function for call to 'Person::(Person*&')

My testing code is this:

#include <iostream>
#include <cstring>

class Person
{
private:
    int* age;
    std::string name;
public:
    Person(std::string name_in, int age_in);
    Person(const Person& other);
    ~Person();
    void printAge();
    void printName();
};

Person::Person(std::string name_in, int age_in)
{
    std::cout << "Creating person named " << name_in << std::endl;
    name = name_in;
    age = new int;
    *age = age_in;
}
Person::Person(const Person& other)
{
    std::cout << "Copying person." << std::endl;
    age = new int;
    *age = *other.age;
    name = other.name;
}
Person::~Person()
{
    std::cout << "Freeing memory!" << std::endl;
    delete age;
}

void Person::printAge()
{
    std::cout << "The age is " << *age << std::endl;
}

void Person::printName()
{
    std::cout << "The name is " << name << std::endl;
}


int main()
{
    Person* person1 = new Person("Ramon", 19);
    person1->printAge();
    person1->printName();

    Person* person2 = new Person(person1);
    person2->printAge();
    person2->printName();

    delete person1;
    delete person2;

    return 0;
}

It seems that when person2 object is created it is just a pointer to person1, but it is not! I stated it to be a new dynamically allocated object: Person* person1 = new Person("Ramon", 19);. Any idea what could be the cause of this?

Thanks.

like image 462
Ramon Blanquer Avatar asked Jun 12 '26 22:06

Ramon Blanquer


1 Answers

A copy constructor takes the input argument by reference, not by pointer.

Change this:

Person* person2 = new Person(person1);

To this:

Person* person2 = new Person(*person1);
like image 64
barak manos Avatar answered Jun 14 '26 13:06

barak manos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!