Return a shared_ptr<Account>
. That way the consumer can call the Account's methods but can't overwrite Person._account.
#include <iostream>
#include <memory>
using std::cout;
using std::endl;
using std::shared_ptr;
using std::wstring;
class Account
{
public:
long Amount;
};
class Person
{
private:
shared_ptr<Account> _account = shared_ptr<Account>(new Account());
public:
wstring Name;
shared_ptr<Account> GetAccount() { return _account; }
shared_ptr<const Account> GetAccount() const { return _account; } // a const Person has a const Account
};
int main()
{
Person p;
shared_ptr<Account> a = p.GetAccount();
a->Amount = 1; // access p.Account
cout << a->Amount << endl; // print 1
Account* b = new Account();
b->Amount = 2;
a.reset(b); // doesn't affect p.Account
cout << p.GetAccount()->Amount << endl; // still 1
}
This works because returning a shared pointer copies it, including the raw pointer. Changes to the shared container affect only the copy but dereferencing the underlying pointer reaches the original instance.