OOP Lecture 2
OOP Lecture 2
Arjay V. Ordonio
Functions
public:
int Addition(int a, int b)
{ Members function are declared as
c = a+b; public.
Note that: Only within the function
return c;
the data members can be
}j manipulated
void Dislay()
{cout << “The sum is: ” << c<<“\n;}
};
Void main()
{
Test obj;
Only member functions are
obj.Addition(10,20); accessible outside outsid the
obj.Display(); class because they are public.
}
Output
The sum is: 30
Write a C++ program to check whether an integer is a Prime or a composite number:
#include <iostream>
using namespace std;
class Test
{
int num;
public:
void Get_num(){
cout<<"Please Enter a positive integer"<<endl;
cin>>num;
}
void Check_prime(){
int flag = 1;
for(int n = 2; n<=num -1; n++){
if(num % n==0){
flag=0;
}
}
if(flag == 1){
cout<<num<<"is a prime number"<<endl;
}
else
cout<<num<<"is a composite number"<<endl;
}
};
void main()
{
Test obj;
obj.Get_num();
obj.Check_prime();
system("pause");
}
Default Arguments
#include <iostream>
using namespace std;
class Test
{
private:
int x, y;
public:
void fun(int x, int y=100){
cout << "x= "<< x <<endl;
cout << "y= "<< y <<endl;
}
};
void main()
{
Test obj;
cout << "Displaying the default argument value" <<
endl;
obj.fun(10);
cout << "Overriding the default argument" << endl;
obj.fun(10,20);
system("pause");
}
Function Overloading
class test{
public:
int sum(int, int);
float sum(float, float);
double sum(double, double);
};
void main(){
test obj;
int choice;
int a,b;
float x,y;
double m,n;
double result = 0;
cout<<"\n\t\t Main Menu";
cout<<"\n\t1. Addition of two integer numbers.";
cout<<"\n\t2. Addition of two float numbers.";
cout<<"\n\t3. Addition of two double numbers."<<endl;
cout<<"\nEnter your choice: ";
cin >> choice;
switch(choice){
case 1: cout <<"\nEnter 2 numbers: ";{
cin>>a>>b;
result = obj.sum(a,b);
break;}
case 2: cout <<"\nEnter 2 numbers: ";
cin>>x>>y;
result = obj.sum(x,y);
break;
case 3: cout <<"\nEnter 2 numbers: ";
cin>>m>>n;
result = obj.sum(m,n);
break;
default:cout <<"\nWrong choice:";
break;
}
cout << "\n\nResult: " << result <<endl;
system("pause");
}