Given the following code:
[example.h]
class MyClass
{
public:
MyClass();
std::string name;
std::string address;
bool method (MyClass &object);
};
[example.cpp]
MyClass::MyClass()
{
}
bool MyClass::method (MyClass &object) {
try {
object.name = "New Name";
std::cout << "Name: " << object.name << " " << object.address << std::endl;
return true;
}
catch (...) {
return false;
}
}
[test.cpp]
#include "example.h"
int main()
{
MyClass myC;
myC.address = "address";
bool quest = myC.method(myC);
}
What is the difference between the way I’ve called myC.method in main above, and this alternative way of doing so:
MyClass *myC = new MyClass();
bool quest = myC.method(*myC);
Which is better and why?
In both cases you can send the same value but simply stick with current code is better since it’s without pointer dereference and
new. You need to take care ofdelete‘ing the object once you are finished with it, which I don’t think you need here.And it’s better to use
MyClass &object constin themethodfunction so that the reference passed in doesn’t get changed.