In C++ I would like to have an instance method return an object reference however the caller should only be allowed to call to access methods of the object in question. In other words the caller should not be allowed to adjust the state of the object referenced by the pointer. Returning a copy of the object would not be ideal when considering performance and the fact that the copy is at a point in time.
Please see my example:
class _balance {
public:
_balance(int pBalance) // Constructor
{setBalance(pBalance);}
int getBalance()
{return bal;}
void setBalance(int pBalance)
{bal = pBalance;}
private:
int bal;
};
class _account {
public:
_account() // Constructor
{balance = new _balance(100);}
_balance *getAccountBalance()
{return balance;}
private:
_balance *balance;
};
int main() {
// Create an account (with initial balance 100)
_account *myAccount = new _account();
// Get a pointer to the account balance and print the balance
_balance *accountBalance = myAccount->getAccountBalance();
printf("Balance is:%d", accountBalance->getBalance() ); // This should be supported
// Changing the balance should be disallowed. How can this be achieved?
accountBalance->setBalance(200);
printf("Adjusted balance is:%d", accountBalance->getBalance() );
}
Resulting Output:
Is there a way to achieve this in c++ Thanks