Category: Object Oriented Programming C++
Object Oriented Programming C++
OOP/CPP program to demonstrate inheritance in area of shapes
OOP/CPP Class for all Arithmetic Operator overloading
OOP/CPP Complex class to demonstrate operator overloading
OOP/CPP String class to add two string and initialize using constructors
OOP/CPP Bank class to deposit, withdraw and display balance of accounts
OOP/CPP Distance class to Convert feet & inches into meter & centimeter and vice versa
OOP/CPP Vector class to create, add, display vector
OOP/CPP demonstrate how friend functions work
/*A C++ program to demonstrate how friend functions work
as a bridge between the classes.
Write a program to find the largest and smallest number
between two numbers of different classes.
*/
#include <iostream>
using namespace std;
class ABC; //forward declaration
class XYZ
{int x;
public:
void setvalue(int i) {x = i;}
friend void max(XYZ, ABC);
friend void min(XYZ, ABC);
};
class ABC
{int a;
public:
void setvalue(int i) {a = i;}
friend void max(XYZ, ABC);
friend void min(XYZ, ABC);
};
void max(XYZ m, ABC n) //definition of friend
{if(m.x >= n.a)
cout << “largest number is:”<<m.x<<endl;
else
cout << “largest number is:”<<n.a<<endl;
}
void min(XYZ m, ABC n) //definition of friend
{if(m.x <= n.a)
cout << “smallest number is:”<<m.x;
else
cout << “smallest number is:”<<n.a;
}
//————————————————————————–//
int main()
{
ABC abc;
abc.setvalue(10);
XYZ xyz;
xyz.setvalue(20);
max(xyz, abc);
min(xyz,abc);
}
OOP/CPP Complex class to add and subtract complex numbers
/* 3. Create a class called COMPLEX
that has two private data called real and imaginary.
Include member function input() to input
real & imaginary values, show() to display complex numbers.
Write a program to add and subtract two complex numbers.*/
#include <iostream>
using namespace std;
class complex // x+iy form
{float x; //real part
float y; //imaginary part
public:
void input (float real, float imag)
{x= real; y = imag;}
friend complex sum(complex, complex);
void subtract(complex, complex);
void show();
};
complex sum(complex c1, complex c2)
{complex c3; //objects c3 is created
c3.x = c1.x + c2.x;
c3.y = c1.y + c2.y;
return(c3); //returns object c3
}
void complex::subtract(complex c1, complex c2)
{x = c1.x – c2.x;
y = c1.y – c2.y;
}
void complex :: show()
{
cout << x << “+j”<< y << endl;
}
int main()
{
complex A,B,C,D;
A.input(3.1, 5.65);
B.input(2.75, 1.2);
C = sum(A, B);
D.subtract(A,B); //C = A + B
cout << “A = “; A.show();
cout << “B = “; B.show();
cout << “C = “; C.show();
cout << “D = “; D.show();
}
Recent Comments