Reputation: 454
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.
Upvotes: 2
Views: 4799
Reputation: 3842
The copy constructor that has been defined is
Person(const Person& other)
This method signature accepts a reference to the object of person, so you would need to send a reference.
In the code you are sending person1 which is a pointer as assigned by the new operator .
If you want to copy an object from pointer of another object than you should be making a method like this.
Person::Person(const Person *other)
{
std::cout << "Copying person." << std::endl;
age = new int;
*age = *other->age;
name = other->name;
}
But this is not a method signature that a copy constructor generally has, and would not copy in situations like
Person p2 = person1;
Upvotes: 1
Reputation: 302
Do make sure to write your own assignment operator also. It is similar to copy constructor but in addition to deep copy of the contents it also returns a reference to the invoking object.
Upvotes: 1
Reputation: 30136
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);
Upvotes: 7