INTRODUCTION OF CONSTRUCTOR
Constructor is a special member function that is used to initialize the member variables of its class, because we cannot initiate any member variable by normal member functions therefore, we need to use constructors.
FEATURES OF CONSTRUCTOR
1. A constructor should be declare with same name of its class name and does not contain any return type statement (such int, char, float, etc.) even void.
2. It automatically executes (call) when we create its class’s object.
3. Constructor should be always declare with public access specifier.
4. In C++ constructors can be classify in three categories (Default, Parameterized and Copy constructor)
DEFAULT CONSTURCTOR
A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values.
DEFAULT CONSTRUCTOR EXAMPLE
#include<iostream.h >
#include<iostream.h >
#include<conio.h>
Class number
{
private:
int a,b;
pubic
// declare a default constructor
number()
{
a=4;
b=7;
}
void sum()
{
cout<<”Sum is:”<<a+b;
}
void main()
{
clrscr();
// Create class object
number ob; // automatically calling the default constructor
ob.sum();
getch();
}
PARAMETERIZED CONSTRUCTOR
When an object is declared in a parameterized constructor, the initial values have to be passed as arguments to the constructor function. The normal way of object declaration may not work. The constructors can be called explicitly or implicitly.
PARAMETERIZED CONSTRUCTOR
#include<iostream.h >
#include<conio.h>
#include<iostream.h >
#include<conio.h>
Class year
{
private:
int a,b;
pubic:
// declare a parameterized constructor
year(int y)
{
int n=y;
}
show()
{
cout<<”Current year is: ”<<n;
}
void main()
{
clrscr();
// Create class object
number ob(2015); // Calling parameterized constructor
ob.show();
getch();
}
COPY CONSTRUCTOR
COPY CONSTRUCTOR EXAMPLE
#include<iostream.h>
#include<iostream.h>
#include<conio.h>
class number
{
private:
int x, y;
public:
number(int x1, int y1) // Parameterized constructor
{
x = x1;
y = y1;
}
// Define copy constructor
number(number &p2)
{
x = p2.x;
y = p2.y;
}
int getX()
{
return x;
}
}
int getY()
{
return y;
}
}
};
void main()
{
clrscr();
number ob1(10, 15); // Parameterized constructor calling here
number ob2 = ob1; // Copy constructor calling here
// Access values assigned by constructors
cout << "ob1.x = " << ob1.getX() << ", ob1.y = " << ob1.getY();
cout << "\nob2.x = " << ob2.getX() << ", ob2.y = " << ob2.getY();
getch();
}
}
0 Comments