Header Ads Widget

Ticker

6/recent/ticker-posts

Practical 8 OOP

 PRACTICAL – 8.1

Create a class sample with members a and b of type integer. Write a friend function that takes an object as argument and calculates the mean of the two members.

#include <iostream>

using namespace std;
class Frnd;
void mean(Frnd &a);
class Frnd
{
    int a, b;

public:
    void setdata()
    {
        cout << "Enter Two Numbers : ";
        cin >> a >> b;
    }
    friend void mean(Frnd &a);
};
void mean(Frnd &a)
{
    cout << "Mean is " << (a.a + a.b) / 2;
}
int main()
{
    Frnd f1;
    f1.setdata();
    mean(f1);
    return 0;
}

PRACTICAL – 8.2

Create  a  class  complex  that  has  two  members  of  type  float.  Write  a  friend  function  that calculate the sum of the two complex objects and returns the result as an object. Demonstrate the working using a main function.

#include <iostream>
using namespace std;
class Complex;
Complex Sum_complex(Complex &r, Complex &j);
class Complex
{
    float num1, num2;

public:
    Complex()
    {
        num1 = 0;
        num2 = 0;
    }
    Complex(float a, float b)
    {
        num1 = a;
        num2 = b;
    }
    void getdata()
    {
        cout << num1 << " + i" << num2 << endl;
    }
    friend Complex Sum_complex(Complex &r, Complex &j);
};
Complex Sum_complex(Complex &r, Complex &j)
{
    Complex sum;
    sum.num1 = r.num1 + j.num2;
    sum.num2 = r.num1 + j.num2;
    return sum;
}
int main()
{
    Complex c1(1.1, 2.2), c2(1.4, 1), c3;
    c3 = Sum_complex(c1, c2);
    c1.getdata();
    c2.getdata();
    c3.getdata();
    return 0;
}

PRACTICAL – 8.3

For the complex Class, demonstrate the use of multiple constructors.Write a program to demonstrate the use of copy constructor.

#include <iostream>
using namespace std;
class Cpy_constructor
{
    int a;

public:
    Cpy_constructor()
    {
        a = 0;
    }
    Cpy_constructor(int x)
    {
        a = x;
    }
    Cpy_constructor(Cpy_constructor &x)
    {
        a = x.a;
    }
    void display()
    {
        cout << a << endl;
    }
};
int main()
{
    Cpy_constructor j;
    j.display();
    Cpy_constructor i(3);
    i.display();
    Cpy_constructor k(i);
    k.display();
    return 0;
}

Post a Comment

0 Comments