Ticker

6/recent/ticker-posts

C++ (Constructor)

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<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>
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
The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously. The copy constructor is used to: Initialize one object from another of the same type. Copy an object to pass it as an argument to a function.

COPY CONSTRUCTOR EXAMPLE
#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();

}









Post a Comment

0 Comments