Page 91 - DCAP404 _Object Oriented Programming
P. 91
Object-oriented Programming
Notes private:
int num1;
int num2;
public:
int add()
{
num1 = 2;
num2 = 3;
int sum = num1 + num2;
return sum;
}
};
int main()
{
Calculator obj;
int result = obj.add();
cout << result;
return 0;
}
The class has two private members (properties) and one public member (method). In the class
description, the add() method uses the names of the private members as identifiers. So the add()
method, a member of the class has accessed the private members of the class.
The main function definition (second line) has been able to access the add() method of the class
because the add() method is public (it has a public access specifier).
The following code will not compile because the main function tries to access (use as identifier)
a private member of the class:
#include <iostream>
using namespace std;
class Calculator
{
private:
int num1;
int num2;
public:
int add()
{
84 LOVELY PROFESSIONAL UNIVERSITY