Professional Documents
Culture Documents
Class:- BEE-3C
Course:- OOP
LAB TASKS
5.1. Code the example given above and check the errors if you try to access the private data
members in main() function.
#include<iostream>
class add
private:
public:
iNum1=iVar1;
iNum2=iVar2;
}
void sum(void)
iNum3=iNum1+iNum2;
void disp(void)
};
int main()
add A1;
cin>>iX;
cin>>iY;
A1.iNum1;
A1.input(iX, iY);
A1.sum();
A1.disp();
system("pause");
}
When I try to access the private data members in main(), it gives error as seen in line 27
because private members are only accessible to the objects they are contained in.
5.2. Modify the above task by making the scope of public member functions as private.
Create access functions in public scope to access private member functions from main().
#include<iostream>
class add
private:
iNum1=iVar1;
iNum2=iVar2;
void sum(void)
iNum3=iNum1+iNum2;
void disp(void)
public:
void access()
cin>>iNum1>>iNum2;
input(iNum1,iNum2);
sum();
disp();
};
int main()
add A1;
A1.access();
return 0;
5.3. Code the example given above and include a private constructor in the class. Create
objects of this class. Test the code and write down how the constructor will be called or
unable to be called?
#include<iostream>
class add
private:
add()
cout<<"This is a constructor"<<endl;
}
public:
iNum1=iVar1;
iNum2=iVar2;
void sum(void)
iNum3=iNum1+iNum2;
void disp(void)
};
int main()
add A1;
A1.add();
return 0;
}
The constructor is unable to be called in main because it is in private and private methods are
only accessible to the objects they are contained in.
HOME TASKS
6.1. Create a class of subtraction having two private data members. Create class methods to
get data from users and for subtraction of data members. Use appropriate access modifiers
for class methods.
#include<iostream>
class subtraction
private:
int num1,num2,num3;
public:
void get_function()
cin>>num1;
cin>>num2;
void sub()
num3=num1-num2;
void disp()
};
int main()
subtraction s1;
s1.get_function();
s1.sub();
s1.disp();
}
CONCLUSION
In this lab I learnt about the public, private and protected scope in a program and
accessing rules of class data members and functions. Moreover I learnt using a
function definition out of the class instead of defining function in class or main.