8/4/2019 OOPS Sample Programs
1/14
OOPS SMALL PROGRAMS
Prepared by
M. Rameshkumar,Lect(CSE)
8/4/2019 OOPS Sample Programs
2/14
Structure of a program#include
int main (){cout
8/4/2019 OOPS Sample Programs
3/14
cin >> i;cout
8/4/2019 OOPS Sample Programs
4/14
#include int main ()
{unsigned long n;
do {
cout > n;cout
8/4/2019 OOPS Sample Programs
5/14
switch (x) {
case 1:case 2:
case 3:
cout
8/4/2019 OOPS Sample Programs
6/14
}float operate (float a, float b)
{return (a/b);
}
int main ()
{int x=5,y=2;
float n=5.0,m=2.0;cout
8/4/2019 OOPS Sample Programs
7/14
return 0;
}
O/P5 10 15
2 4 6 8 10
Pointers#include
int main (){int value;
int * mypointer;
mypointer = &value;*mypointer = 10;
cout
8/4/2019 OOPS Sample Programs
8/14
int area (void) {return (width*height);}
};
int main () {CRectangle rect (3,4);
CRectangle rectb;
cout
8/4/2019 OOPS Sample Programs
9/14
void main () {CDummy a;
a.disp();CDummy b;
b.disp();
CDummy c;
c.disp();}
O/P1
2
3
Friend functions#include
class CRectangle {
int w;public:
void set_values (int a, int b)
{w = a;
}int print () {return w;}friend CRectangle duplicate (CRectangle);
};
CRectangle duplicate (CRectangle rectparam){CRectangle rectres;
rectres.w = rectparam.w*2;
return (rectres);
}int main () {CRectangle rect, rectb;
rect.set_values (2);
rectb = duplicate (rect);cout
8/4/2019 OOPS Sample Programs
10/14
{protected:
int avoid geta(int x)
{
a=x;
}void printa()
{cout
8/4/2019 OOPS Sample Programs
11/14
#include
class Base1 {protected:
int a;
public:
Base1( int Value ){
a = Value;}int getData()
{
return value;}
};class Base2
{
protected:int b;
public:
Base2( int value2 ){
b = value2;}char getData()
{
return letter;
}};class Derived : public Base1, public Base2
{
private:
int c;public:Derived( int val1, int val2)
: Base1( val1 ), Base2( val2) { }
}
void display(){
c=a+b;
cout
8/4/2019 OOPS Sample Programs
12/14
tot = sub1+sub2+e;put_num();
put_marks();put_extra();
cout
8/4/2019 OOPS Sample Programs
13/14
bptr->print();bptr = &two;
bptr->print();return 0;
}
O/PDerived2
Derived1Derived2
TemplatesThe format for declaring function templateswith type parameters is:
Syntaxtemplate
function_declaration;
template function_declaration;
Function template#include
template T GetMax (T a, T b) {T result;
result = (a>b)? a : b;
return (result);
}
int main () {
int i=5, j=6, k;
long l=10, m=5, n;
k=GetMax(i,j);n=GetMax(l,m);cout
8/4/2019 OOPS Sample Programs
14/14
Input/Output with files ofstream: Stream class to write on
files
ifstream: Stream class to read fromfiles
fstream: Stream class to both read andwrite from/to files.
Basic file operations#include
#include
using namespace std;int main () {
ofstream myfile;myfile.open ("example.txt");
myfile