I have created the following class.
class Persona{
private:
std::string nombre;
public:
std::string getNombre();
Persona operator=(std::string nombre);
};
Persona Persona::operator=(std::string nombre){
Persona persona;
persona.nombre = nombre;
return persona;
}
std::string Persona::getNombre(){
return this->nombre;
}
As you can see, the operator is overloaded =
:
Persona operator=(std::string nombre);
What I want is to be able to assign the value to the attribute nombre
using the operator =
.
Leaving my code like this:
#include <iostream>
#include <cstdlib>
#include <string>
class Persona{
private:
std::string nombre;
public:
std::string getNombre();
Persona operator=(std::string nombre);
};
Persona Persona::operator=(std::string nombre){
Persona persona;
persona.nombre = nombre;
return persona;
}
std::string Persona::getNombre(){
return this->nombre;
}
int main(void)
{
Persona p;
p = "John Doe";
std::cout << "Nombre: " << p.getNombre() << std::endl;
return EXIT_SUCCESS;
}
When compiling, there are no errors, based on what I've read, the operator =
makes a return, and this is assigned to the object where it is used:
p = "John Doe";
But! When I run the program, I get this:
Name:
Process returned 0 (0x0) execution time : 0.015 s
Press any key to continue.
The value that should be assigned is not assigned, leaving the name empty.
What mistake am I making in overloading operator = ?
The correct thing would be (I show it inline for brevity):
To access the members of our own class, we don't need to precede them with the class name; all members become accessible from the body of the functions, as if they were local variables of the function. It is a facility that the language offers to the programmer.
For the same reason, it is not necessary to access them as
this->ALGO
; that would be used in case of name conflict; for example, receiving a method argument with the same name as an attribute of the class.In your original code, inside
operator=( )
, you create a new instance of the classPersona
, assign to that instance, and then return that instance you created. Doing so leaves the original instance intact .Also notice that I have changed the return value of your
operator=
. Instead of returning an instance, I return a reference to the original instance .