Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

Parameterized constructor in C++

parameterized constructor in c++

What is parameterized constructor in C++?

A constructor is a special member function whose task is to initialize the objects of its class. It is special because its name is same as the class name. The constructor is invoked whenever an object of its associated class is created.  A constructor, constructs the values of data members of the class hence it is called as constructor. In C++ there are three types of constructor namely:-

      • Default constructor
      • Parameterized constructor
      • Copy constructor

Let us learn about parameterized constructor in C++ more, in this article.

Parameterized constructor in C++

In simple words, constructors that can take arguments are called parameterized constructors. Whenever there is necessity to initialize the various data elements of different objects with different values when they are created then this necessity can be fulfilled by passing arguments to the constructor function when the objects are created. And this argument passing   in C++ is possible by using parameterized constructor . Parameterized Constructors can exist even without the existence of Default Constructors.

  • Benefits of parameterized constructor in C++

      • Parameterized constructor helps in initializing each instance of the class to different values.

      • Parameterized constructor is helpful for constructor overloading.

 

Syntax for declaring parameterized constructor inside the class

class class_name 
{

public:
  class_name(variables) //Parameterized constructor declared.
  {
  
  }
};

Syntax for declaring parameterized construct outside the class

class class_name
{
   
};
class_name :: class_name() //Parameterized constructor declared.
{
      
}

C++ program to demonstrate parameterized constructor

#include <iostream> 
using namespace std; 
  
class PrepInsta 
{ 
private: 
    string st; 
  
public: 
     
    PrepInsta(string str)//Parameterized Constructor 
    { 
        st=str; 
    } 
  
    string getst() 
    { 
        return st; 
    } 
    
}; 
  
int main() 
{ 
    //Constructor called. 
    PrepInsta p("Learning is fun with PrepInsta"); 
    cout <<p.getst(); 
  
    return 0;
}