Sie sind auf Seite 1von 10

CONSTRUCTORS

CONSTRUCTORS
• A constructor is aspecial member function for
automatic initialization of an object.
• Whenever the object is created ,a special
member function that is constructor is called
automatically.
• A constructor function is different from all
other nonstatic member function in a class
because it is used to initialize the variables of
whatever instance being created.
RULES FOR WRITING
CONSTRUCTOR FUNCTION
• A constructor name must be same as that of
class name.
• It is declared with no return type
• It can not be declared as static,virtual,const or
volatile.
Syntax

class user
{
private:
----------
----------
public:
user();//constructor
};
User::user() // constructor definition
{
---------------------
---------------------
}
Types of constructors
• Default constructor
• Parameterized constructor
• Copy constructor
• Dynamic constructor
Default constructor
The default constructor is a special member function which is
invoked by c++ compiler without any argument for initializing
the objects of a class.
for example:
class student
{
private:
char name[20];
long int rollno;
public:
Student();//default constructor
void display();
};
Parameterized constructors
When we pass arguments to the constructor function when the objects are
created. The constructor that takes arguments are called parameterized
constructors.
For example:
class integer
{
int m,n;
public:
integer(int,int) ;//parameterized constructor
void display()
{ cout<<“m =“<<m<<endl;
cout<<“n=“<<n<<endl;
}

};
To be continued:
contniued……..
integer::integer(int x, int y)
{
m=x;
n=y;
}
void main()
{
integer obj(10,100);
Obj.display();
getch();
}
Copy constructor
Copy constructor are always used when the compiler has
to create a temporary object of a class object. The copy
constructors are used in the following situations :
• The initialization of an object by another object of
same class
• Return of objects as function value.
• Stating the object as by value parameters of a function
General syntax:
class_name::class_name(class_name &ptr)
Example of copy constructor
class fibonnacci
{ c=ptr.c;
private: a=b;
int a,b,c; b=c;
public: c=a+b;
fibonacci(); }
fibonacci(fibonacci &ptr); void fibonacci:: display()
void display(); {
}; cout<<c<<“\t”;
fibonacci::fibonacci() }
{ void main()
a=0; {
b=1; fibonacci obj;
c=a+b; for(i=0;i<15;i++)
} {
fibonacci::fibonacci(fibonacci &ptr) obj.display();
{ }
a=ptr.a; getch();
b=ptr.b; }

Das könnte Ihnen auch gefallen