0

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:

enter image description here

Is there a way to achieve this in c++ Thanks

3 Answers3

1

Use the keyword const.

const _balance* accountBalance = myAccount->getAccountBalance();

this makes it so the members are constant so they can't be modified. This also means you can only call balance member functions that are marked const. Since getBalance() does not modify the value, it can be marked const

        int getBalance() const // <----
            {return bal;}
kmdreko
  • 42,554
  • 6
  • 57
  • 106
1

Return a 'const _balance*'. All non const methods will by default be disallowed.

cjhanks
  • 526
  • 4
  • 4
0

Re

the caller should not be allowed to adjust the state of the object referenced by the pointer

Well, you know, that's what const is all about.

You need a good textbook. Check out the SO C++ textbook FAQ.

Community
  • 1
  • 1
Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331