Constructor In C++

Introduction

It is special member function of the class.
It has same name of class.
It is automatically called when object(instance of class) create.
It must be a public member.
No Return Values.

Constructor General Form:


class class-name
{
    Access Specifier:
        Member-Variables
        Member-Functions
    public:
        class-name()
        {
            // Constructor code
        }

        ... other Variables & Functions
}

Constructor Example:
Program:


class Example        {
    int a,b;
    public:

    //Constructor
    Example()            {
    a=10;
    b=20;
    cout<<"Im Constructor"
    }

    void Display()    {
    cout<<"Values :"<<a<<"\t"<<b;
    }
}

int main()                {
        Example Object;
        // Constructor invoked.
        Object.Display()
        return;
}

Output:
10 20

Parameterized Constructor:
Which constructor has arguments thats called Parameterized Constructor.

Parameterized Constructor General Form:

class class-name
{
    Access Specifier:
        Member-Variables
        Member-Functions
    public:
        class-name(type Variable,type Varibale2......)
        {
            // Constructor code
        }

        ... other Variables & Functions
}

Parameterized Constructor Example:
Program:


class Example        {
    int a,b;
    public:

    //Constructor
    Example(int x,int y)            {
    a=x;
    b=y;
    cout<<"Im Constructor"
    }

    void Display()    {
    cout<<"Values :"<<a<<"\t"<<b;
    }
}

int main()                {
        Example Object(10,20);
        // Constructor invoked with parameters.
        Object.Display()
        return;
}

Output:
10 20

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s