Pages

Showing posts with label FUNCTION OVERLOADING. Show all posts
Showing posts with label FUNCTION OVERLOADING. Show all posts

Wednesday, August 15, 2012

FUNCTION OVERLOADING - Program to create a class called complex

Write a C++ program to create a class called COMPLEX and implement the following overloading functions ADD that return a COMPLEX number .
I. ADD(a,s2) - where a is an integer(real part) and s2 is a complex    number.
II. ADD(s1,s2) - where s1 and s2 are complex objects.


#include<iostream.h>
#include<conio.h>
class complex
{
  int r,i;
  public:
  void read();
  void print();
  friend complex add(int a,complex c);
  friend complex add(complex c1,complex c2);
};
void complex::read()
{
  cout<<"Enter real and imaginary\n";
  cin>>r>>i;
}
void complex::print()
{
  cout<<r<<"+i"<<i<<endl;
}
complex add(int a,complex c)
{
  complex t;
  t.r=a+c.r;
  t.i=c.i;
  return t;
}
complex add(complex c1,complex c2)
{
  complex t;
  t.r=c1.r+c2.r;
  t.i=c1.i+c2.i;
  return t;

}
void main()
{
   int a=2;
   clrscr();
   complex s1,s2,s3;
   s1.read();
   cout<<"\ns1 : ";
   s1.print();
   s2=add(a,s1);
   cout<<"s2 : 2+s1\n";
   cout<<"   : ";
   s2.print();
   s3=add(s1,s2);
   cout<<"s3=s1+s2\n";
   cout<<"s1 : ";
   s1.print();
   cout<<"s2 : ";
   s2.print();
   cout<<"s3 : ";
   s3.print();
   getch();
}

output



Sunday, August 5, 2012

CONSTRUCTOR OVERLOADING

Program to find the area of a rectangle using constructor overloading.


#include<iostream.h>
#include<conio.h>
class area
{
   int a,l,b;
   public:
   area() // simple constructor definition.
   {
      l=5;
      b=6;
      cout<<"Simple constructor called\n";
      cout<<"length="<<l<<"\nbreadth="<<b<<endl;
   }
   area(int x,int y) // parameterised constructor
   {
      l=x;
      b=y;
   }
   void calc();
   void print();
};
void area::calc()
{
    a=l*b;
}
void area::print()
{
    cout<<"Area is : "<<a<<endl;
}
void main()
{
    int l,b;
    clrscr();
    area a1; // simple constructor is called.
    a1.calc();
    a1.print();
    cout<<"Enter length and breadth for parameterised         constructor:\n";
    cin>>l>>b;
    area a2(l,b); // parameterised constructor is called.
    a2.calc();
    a2.print();
    getch();
}

output