When making class how to access private variable

lets say the class has a private variable double a
and only one public function double Calculate(double b, double c) that returns
a*b*c.

I want to change the value of private variable.

How do you access private variable?
Last edited on
closed account (zb0S216C)
External methods and variables cannot access private members of a given class. However, integrating two class methods that return and modify the private member is possible. An example of this is below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class MyClass
{
    public:
        MyClass( void )
        {
             PrivateMember = 0;
        }

        int GetPrivateMember( void ) const
        {
             return PrivateMember;
        }

        void SetPrivateMember( const int New = 0 )
        {
             PrivateMember = New;
             return;
        }

    private:
        int PrivateMember;
} NewClass;

int ExternalVariable( NewClass.GetPrivateMember( ) );   // This is allowed.
int ExternalVariable( NewClass.PrivateMember );         // This is not allowed. 


I hope this helps.
Last edited on
Topic archived. No new replies allowed.