PARAMETERIZED CONSTRUCTOR IN C++

 Que - What is parameterized constructor?

Ans. Parameterized constructor:-

Parameterized constructor is that Constructor in which we pass the parameters. It is possible to pass arguments to constructors. Typically, these arguments help initialize an object when it is created. To create a parameterized constructor, simply add parameters to it the way you would to any other function. When you define the constructor’s body, use the parameters to initialize the object. 

Advantages of parameterized constructor:-

  1. A Class or Struct can have multiple parameterized constructors as long as they have different method signature. They follow the same concept of method overloading.
  2. Compiler provides Default Constructors only if there is no constructor (Default or Parameterized) defined in a class.
  3. Parameterized Constructors can exist even without the existence of Default Constructors.
  4. The advantage of a parameterized constructor is that you can initialize each instance of the class to different values.

Example of parameterized constructor:-

#include<iostream>
using namespace std;

class krishna
{
public:
    int radius;
    float area,pi;
public:
    krishna (int rad)
    {
        radius =rad;
        area=3.14*radius*radius ;
    }
};
int main()
{
    int rad;

    cout<<"enter radius of circle :-";
    cin>>rad ;

    krishna ob ( rad) ;

    cout<<"area of circle is:-"<<ob.area<<endl;
    return 0;
}

Result:-





Post a Comment

Previous Post Next Post