Parameterized constructors

 Parameterized constructors:

 

A constructor that takes one or more arguments is called parameterized constructor.

Using this constructor, it is possible to initialize different objects with different values.

Parameterized constructors can be overloaded.

Syntax:

class classname

{

            private:

                        ---------

            pubic:

                        classname(arguments)

                        {

                                    ------------

                        }

};

 

Parameterized constructors can be invoked in following methods

1.    Explicit call: In this, declaration of an object followed by assignment operator, constructor name and argument list in parenthesis.

Syntax: classname objectname=constructorname(arguments);

2.    Implicit call: In this, declaration of an object followed by dot operator, constructor name and argument list in parenthesis.

Syntax:classname objectname.constructorname(arguments);

3.    Initializing at the time of declaration with = operator: This method used when constructor contains only one argument.

Syntax: classname objectname=value;

 

Ex:

 

class number

{

            privae:

                        int n,m;

            public:

                        number(intx,int y)

                        {

                                    n=x;

                                    m=y;

                        }

                        void display( )

                        {

                                    cout<<n<<m;

                        }

};

void main( )

{

            number n1=number(15,25);       //explicit call

            number n2.number(10,20);         //implicit call

            number n3(30,10);                        //implicit call

            n1.display( );

            n2.display( );

            n3.display();

}

Comments