A. Wolf
A. Wolf

Reputation: 1347

Define operator = with std::string

Good morning! I'm trying to define the assignment operator for a class like this:

Person {
string name;int age;
Person(string name,int age);
}

I know that if name would be a char*, I've first to delete the previous version of name, make it NULL and allocate a new array of char. Now I've a string, so what I've to do?
I thought to write something like this:

Person(const Person& copy){
this->name=copy.name;
this->age=copy.age; }

but it doesn't work. I tried to delete the string name, but the compiler gives me an error. Where is the problem? Thank you!

Upvotes: 0

Views: 261

Answers (3)

eerorika
eerorika

Reputation: 238361

I know that if name would be a char*, I've first to delete the previous version of name, make it NULL and allocate a new array of char

Assuming the class "owns" the pointed array, that is correct.

Now I've a string, so what I've to do?

In the copy assignment operator, you will need to copy assign the member string just like you do with the int.

That's exactly what the implicit, compiler generated copy assignment operator does, so you don't need to declare one yourself at all.

I thought to write something like this:

Person(const Person& copy)

That's a copy constructor. You don't need to declare that either, because the implicitly generated one does exactly what you want.

but the compiler gives me an error. Where is the problem?

The problem will be in the location indicated by the error message.


TL;DR you don't need to add a custom copy assignment, nor copy constructor at all.

Upvotes: 0

marcinj
marcinj

Reputation: 49986

This:

Person(const Person& copy){

is a copy constructor, if you want assignment operator then use;

Person& operator=(const Person& rop) {
   name=rop.name;
   age=rop.age;
   return *this;
}

But the compiler with synthesize a copy-assignment operator if the class does not define one - the same applies to copy constructor. So its unclear to me where is your problem.

You are right that if you have a char* which is assigned buffer from dynamic allocation, then you must manage its lifetime yourself (or using smart pointer). But with std::string or any other class which uses RAII idiom, you use the so called rule of zero, so no need to worry about writing code to make copies.

Upvotes: 1

WhiZTiM
WhiZTiM

Reputation: 21576

That is not an assignment operator. Rather, its a Copy Constructor. You define your Copy assignment operator like this:

Person& operator = (const Person& other)
{
    name= other.name;
    age=  other.age;
    return *this;
}

Upvotes: 1

Related Questions