Creating an object with new keyword:
#include <iostream>
#include <string>
using namespace std;
class Person {
private:
string name;
public:
Person(string name) {
setName(name);
}
string getName() {
return this->name;
}
void setName(string name) {
this->name = name;
}
};
int main() {
Person *person1 = new Person("Rajat");
Person *person2 = person1;
person2->setName("Karan");
cout << person1->getName() << endl;
cout << person2->getName() << endl;
return 0;
}
Output:
Karan
Karan
Creating an object without new keyword:
#include <iostream>
#include <string>
using namespace std;
class Person {
private:
string name;
public:
Person(string name) {
setName(name);
}
string getName() {
return this->name;
}
void setName(string name) {
this->name = name;
}
};
int main() {
Person person1("Rajat");
Person person2 = person1;
person2.setName("Karan");
cout << person1.getName() << endl;
cout << person2.getName() << endl;
return 0;
}
Output:
Rajat
Karan
I expected the output to be 'Karan Karan' as I thought in Person person2 = person1, person2 refers to the same person1. But it isn't the case.
Can someone please explain what does the line Person person2 = person1 do under the hood? Does it create a totally new object?