Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconFull Stack Developmentbreadcumb forward arrow iconParameterized Constructor In C++: Working & Examples

Parameterized Constructor In C++: Working & Examples

Last updated:
27th May, 2021
Views
Read Time
6 Mins
share image icon
In this article
Chevron in toc
View All
Parameterized Constructor In C++: Working & Examples

In my years of experience in software development, I’ve come to appreciate the foundational concepts that make programming languages like C++ so powerful and versatile. One such concept that has significantly impacted how I approach object-oriented programming is the “Parameterized Constructor in C++. ” T

his feature, although seemingly straightforward, has been a game-changer in the way I design and implement my classes. It’s not just about initializing objects; it’s about doing so in a way that’s both efficient and tailored to the specific needs of the application right from the start.  In this article, I’ll cover the basics, delve into how they work, and explore their importance in crafting effective C++ code. Whether you’re new to the field or looking to enhance your understanding of C++, this discussion on parameterized constructors is designed to equip you with a deeper understanding of one of the language’s key features.

What is Constructor?

A constructor is a class’s member function that is used to initialize objects in a class. In C++, when an object which is the class’s instance, is created, the constructor is called automatically. Thus, a constructor is a special member function of the class.

What is a Parameterized Constructor?

Arguments can be passed to constructors. When an object is created, these arguments help initialize an object. To create a parameterized constructor in C++, we can add parameters to a function like it can be added to any other function. When the body of the constructor is defined, the parameters are used to initialize the object.

Ads of upGrad blog

Check out our free courses to get an edge over the competition.

Explore Our Software Development Free Courses

Syntax of Parameterized Constructor in C++

class name_of_class{

Access specifier (Public/protected/private):

Member variables

Member functions

public:

name_of_class(variables){ //Code for constructor

}

// other functions and variables

}

Check out upGrad’s Java Bootcamp

The syntax included having name_of_class, followed by an access specifier that contains member functions and member variables. All these are included in the constructor code, which means that it can be called in the constructor’s body.

Also Read:  Open Source Projects for C++

Example of Parameterized Constructor in C++

#include <iostream>

using namespace std;

 

class Example

{

private:

                     int a, b;

 

public:

                     // Parameterized Constructor

                     Example(int a1, int b1)

                     {

                      a = a1;

                      b = b1;

                     }

 

                     int getA()

                     {

                      return a;

                     }

                     int getB()

                     {

                      return b;

                     }

};

int main()

{

                     // Calling the constructor

                     Example e1(5, 10);

 

                     cout << “e1.a = ” << e1.getA() << “, e1.b = ” << e1.getB();

 

                     return 0;

}

Output

Explanation: Private variables a and b are declared in the class Example. A parameterized constructor is declared using the function Example. It includes two methods getA() and getB(). In the main class, the constructor is called, and the constructor’s access values are assigned.

Check out upGrad’s: Advanced Certification in Blockchain 

Explore our Popular Software Engineering Courses

upGrad’s Exclusive Software and Tech Webinar for you –

SAAS Business – What is So Different?

 

How Does the Parameterized Constructor in C++ Work?

 An object gets initiated, which holds values or the details and parameters the object will process or contain whenever a parameterized constructor in C++ is defined. Then it becomes possible for arguments to be passed to that object. The procedure is very similar to passing a value to a function. It also holds a similarity to passing parameterized values to the objects. 

The objects which are defined in the body of the constructor are initialized using the parameters. The values should be passed as arguments to the constructor function whenever a parameterized constructor is declared. These constructors can be called both explicitly or implicitly. The conventional way of object declaration does not work.

Note: Types of call-

  1. Explicit call- Example e1= Example(0,10)
  2. Implicit call- Example e1(0,10)

Checkout: Project Ideas in C++ for Beginners

What is the Use of Parameterized Constructor in C++?

 The uses of parameterized constructors are as follows:

  • Constructor overloading
  • Used to assign different values to the various data elements of different objects when they are initialized/created

Another example:

1. Program to calculate the area of a rectangle

#include <iostream>

using namespace std;

// declaring a class

class rectangle {

   private:

       double length;

       double breadth;

   public:

       // creating parameterized constructor

       rectangle(double len, double brt) {

                 // initialize private variables

                 length = len;

                 breadth = brt;

       }

       double calculateArea() {

                 return length * breadth;

       }

};

int main() {

       // creating objects and initializing data members

       rectangle rect1(10, 8.6);

       rectangle rect2(8.5, 6);

       cout << “Area of rectangle 1: ” << rect1.calculateArea() << endl;

       cout << “Area of rectangle 2: ” << rect2.calculateArea() << endl;

       return 0;

}

Output

Explanation: In this example, we have created a parameterized constructor rectangle() with two parameters: double len and double bdt. These parameters contain values that are used to initialize the member variables length and breadth. When we create an object of the Rectangle class, we pass the member variables’ values as arguments. We can calculate the area with the calculateArea() function when the member variables are initialized.

1. Displaying marks of students

 #include <iostream>

using namespace std;

        class Student {

          public:

          int std_id;//data member 

          string std_name;//also instance variable

          float std_marks;

          Student(int i, string a, float b) 

           

                std_id = i; 

                std_name = a; 

              std_marks = b;

    

          void display() 

         

                    cout<<std_id<<”  “<<std_name:<<”  “<<std_marks <<endl; 

           

        };

        int main(void) {

        Student s1 =Student(101, “Soniya”, 89); //creating an object of student

        Student s2=Student(102, “Nakul”, 59);

        s1.display(); 

        s2.display();         return 0;

        }

Output

 Explanation: id, name, and marks are data members (also instance variables). A student is a parameterized constructor, and its objects are created in the main class.

Ads of upGrad blog

Learn Software development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Read our Popular Articles related to Software Development

Conclusion

Constructors are just special kinds of methods in which we can pass values. If we do not pass values to the constructor, then the end object has some default value. [1] [MOU2] The objects hold the methods and values of member variables that are part of the main class. These values are finally passed via constructors. A parameterized constructor in C++ has its advantage of assigning different objects different values, and there can be overloading.

Now that you are aware of the parameterized constructors in C++, if you want to dig deeper and move up in your programming career, then explore courses from upGrad, India’s largest online higher education company. You must check our Full-Stack Software Development Programme.

Profile

Rohan Vats

Blog Author
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Frequently Asked Questions (FAQs)

1What is a constructor?

Constructor is a special method in a class which has the same name as the class. It is special because this method is automatically called when a class is created (instantiated). If a constructor has no arguments, then the class is being instantiated with empty values. Constructor performs initialization tasks and initializes the instance variables of the class. The main purpose of constructor is to establish the values of the object's properties. It is also used to perform any operation that need to be executed only once. Constructor is usually declared as a public static in the class and the object is created using this constructor.

2How many constructors can there be in a class?

If we are talking about C++, then the number of constructors is unlimited. However, there may be other limits because of other reasons such as the memory limitation of your machine, the complexity of the class, etc. Therefore, the number of constructors is unlimited, but the number of constructor parameters is not. There can be as many constructors in a class as you want. But the default constructor is a must. Any class which has no default constructor is an abstract class. Abstract class cannot be instantiated.

3What is object-oriented programming?

Object oriented programming is a programming paradigm that treats ‘objects’ as the fundamental building blocks of a program or computer system. Objects are software entities that can contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods. Object oriented programming focuses on data and the rules surrounding it, rather than focusing on procedural logic or flow-of-control, as was common in early programming languages. OOP deals with data as a whole rather than as a set of individual elements.

Explore Free Courses

Suggested Blogs

Top 7 Node js Project Ideas &#038; Topics
31576
Node.JS is a part of the famous MEAN stack used for web development purposes. An open-sourced server environment, Node is written on JavaScript and he
Read More

by Rohan Vats

05 Mar 2024

How to Rename Column Name in SQL
46940
Introduction We are surrounded by Data. We used to store information on paper in enormous file organizers. But eventually, we have come to store it o
Read More

by Rohan Vats

04 Mar 2024

Android Developer Salary in India in 2024 [For Freshers &#038; Experienced]
901325
Wondering what is the range of Android Developer Salary in India? Software engineering is one of the most sought after courses in India. It is a reno
Read More

by Rohan Vats

04 Mar 2024

7 Top Django Projects on Github [For Beginners &amp; Experienced]
52108
One of the best ways to learn a skill is to use it, and what better way to do this than to work on projects? So in this article, we’re sharing t
Read More

by Rohan Vats

04 Mar 2024

Salesforce Developer Salary in India in 2024 [For Freshers &#038; Experienced]
909197
Wondering what is the range of salesforce salary in India? Businesses thrive because of customers. It does not matter whether the operations are B2B
Read More

by Rohan Vats

04 Mar 2024

15 Must-Know Spring MVC Interview Questions
34760
Spring has become one of the most used Java frameworks for the development of web-applications. All the new Java applications are by default using Spr
Read More

by Arjun Mathur

04 Mar 2024

Front End Developer Salary in India in 2023 [For Freshers &#038; Experienced]
902389
Wondering what is the range of front end developer salary in India? Do you know what front end developers do and the salary they earn? Do you know wh
Read More

by Rohan Vats

04 Mar 2024

Method Overloading in Java [With Examples]
26238
Java is a versatile language that follows the concepts of Object-Oriented Programming. Many features of object-oriented programming make the code modu
Read More

by Rohan Vats

27 Feb 2024

50 Most Asked Javascript Interview Questions &#038; Answers [2024]
4386
Javascript Interview Question and Answers In this article, we have compiled the most frequently asked JavaScript Interview Questions. These questions
Read More

by Kechit Goyal

26 Feb 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon