Page 90 - DCAP404 _Object Oriented Programming
P. 90
Unit 4: Classes and Objects
int num2; Notes
int add()
{
int sum = num1 + num2;
return sum;
}
};
int myFn(int par)
{
return par;
}
int main()
{
Calculator obj;
obj.num1 = 2;
obj.num2 = 3;
int result = obj.add();
cout << result; cout << “\n”;
int myVar = myFn(obj.num1);
cout << myVar;
return 0;
}
There are two functions in the code: myFn() and main(). The first line in the main function
instantiates a class object called, obj. In main, lines 2 and 3 use the properties of the class as
identifiers. Because the class members are public, the main() function can access the members of
the class. Line 4 of the main function also demonstrates this. In line 6 of the main function, the
function, myFn() uses the property num1 of the class as its argument. It could do so because the
member, num1 is public in the class.
4.5.2 The Private Access Specifier
With the private access specifier an external function cannot access the private members of the
class. With the private specifier only a member of a class can access the private member of the
class. The following code shows how only a member of a class can access a private member of
the class (read the explanation below):
#include <iostream>
using namespace std;
class Calculator
{
LOVELY PROFESSIONAL UNIVERSITY 83