struct constructor with parameters in C++

Structure is a user defined datatype. In C++, it is a collection of data members and member functions inside a single unit. It contains variables of different datatype. Unlike C, Structures in C++ can have Constructor. The struct keyword is used to define structure type user defined datatype and then the name of the structure. We can declare one or more data members and member functions(constructors and other functions) inside the structure definition.

We can define different constructors like default constructor, parameterized constructors inside them.  Let us see how we can implement parameterized constructor inside the structure definition in C++.

The parameters of parameterized constructor help in initializing an object when it is created. We can create a parameterized constructor by simply adding parameters to it. In this tutorial, we will learn struct constructors with parameters in C++ and also learn how to define them inside the structure.

Parameterized constructor inside structure in C++

Constructors are the most important feature of C++ that makes the initialization of structure convenient. Parameterized constructors contain one or more than one parameter to initialize the value of the object created.  It has certain properties:

  • It does not have a return type like any other function.
  • It has the same name as the structure name.
  • It is generally used to initialize objects with the parameter value that is passed through it during object creation.

Syntax:

struct structName
{
    datatype1 variable1;
    datatype2 variable2;
    .
    .
    structName(datatype1 variable1, datatype2 variable2 ...)
    {
          // initialize variables with the value given in parameter
    }
}; 

We will understand this more using an example code here.

#include <bits/stdc++.h>
using namespace std;

// structure definition 
struct Box 
{ 
    float length; 
    float breadth; 
    float height; 
    // Parameterized constructor
    Box(float l, float b, float h) 
    {
        length = l;
        breadth = b;
        height = h; 
    }
    void volume()
   {
       cout<<"Area of Box is "<<length*breadth*height<<endl; 
   }
};
//main function 
int main()
{
    Box b1(10, 2.3, 2.1);
    b1.volume();
    return 0;
}

Output:

Area of Box is 48.3

In this above example, we have created the structure of Box type in which we have declared the length, breadth, height as its data members, and then we have defined parameterized constructor in which there are three parameters of float type which is used to initialize data members of Box type structure.

Leave a Reply

Your email address will not be published. Required fields are marked *