Tuesday 21 August 2018


Constructors

A Constructor is a special member function, which is used to initialize the objects of its class. The Constructor is invoked whenever an object of its associated class is created. The constructor constructs the value of data members of the class.

Features :
  • They are invoked automatically when the objects are created.
  • They do not have return type not even void.
  • The compiler calls constructor implicitly as soon as an object of its type is created.
  • Constructors can be overloaded.
  • The constructor name is same as class name.
Syntax:

                        Class class_name

                        {
                                    data members;
                                    class_name();
                        };
                        classname::classname()
                        {
                                    ----------------
                                    ----------------
                        }
Example:
                        Class sample
                        {
                                    sample();
                        };
                        sample::sampe()
                        {
                                    cout<<”constructor Demo”;
                        }
Program:
class complex
{
int real,img;
complex(){ }
complex(int a)
{
real=img=a;
}
complex(int x,int y)  //parameterized constructor
{
real=x;
img=y;
}
complex sum(complex c1,complex c2)
{
complex c3=new complex();
c3.real=c1.real+c2.real;
c3.img=c1.img+c2.img;
return c3;
}
void display()
{
System.out.println(real+"+i"+img);
}
}
class complexnum
{
public static void main(String args[])
{
complex c1=new complex(1,2);
complex c2=new complex(2);
complex c3=new complex();
c3=c3.sum(c1,c2);
c3.display();
}
}
Output:
C:\>javac complexnum.java
C:\>java complexnum
3+i4

No comments: