Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

Parameterized Constructor In C++: Working & Examples

Updated on 05 December, 2024

37.3K+ views
12 min read

Think of building a custom computer. Instead of getting a one-size-fits-all model, you select the features—RAM, storage, and processor—that match your personal preferences. This is precisely what a parameterized constructor does in C++: it lets you define specific values for each object right when it’s created, tailoring it to your exact needs.

Do you know why it is important to initialize objects in a programming language? It saves your time and eliminates repetitive setup. It enhances the efficiency of your code by allowing you to set unique values for each object during its creation. In this blog, we’ll explore how to use a parameterized constructor in C++, along with its syntax. Let’s dive in!

What Is a Constructor in C++?

A constructor in C++ is a special method in a class that is automatically called when you create an object of that class. Its function is to set things up for the object, such as giving it default values or initializing the resources it needs to work correctly.

In layman's terms, the constructor in C++ is like the setup instructions you have to follow when assembling a piece of furniture or a gadget.

Also Read: Constructors in C++

Now that you have a basic understanding of a constructor let’s dive deeper into parameterized constructors in C++.

What Is a Parameterized Constructor in C++?

A parameterized constructor in C++ is a type of constructor that takes arguments (parameters). Giving arguments allows you to initialize an object with specific values when you create it instead of always providing the object's default values.

Here are the reasons you must use a parameterized constructor in C++.

  • Customization

The parameterized constructor allows an object to start with its own unique set of values. For example, you can create one Car object with a top speed of 180 and another with a top speed of 240.

  • Efficiency

You have to manually set the values after creating the object if you don’t use parameterized constructors.

  • Cleaner code

You can reduce repetitive code by using the parameterized constructor. Instead of writing separate statements to set each data member, you can initialize them all in the constructor.

For illustration, consider the following example.

  • Imagine a class Car where every car has a brand and a top speed. A parameterized constructor allows you to specify the brand and top speed for each car.
  • The Car class has a parameterized constructor Car(string b, int s), which takes two arguments: a brand and a top speed.
  • When you create objects like car1 and car2, you provide specific values for their brand and topSpeed.
  • Each object gets initialized with its own unique values.

Code snippet:

#include <iostream>
using namespace std;

class Car {
    string brand;
    int topSpeed;

public:
    // Parameterized constructor
    Car(string b, int s) {
        brand = b;
        topSpeed = s;
    }

    void displayInfo() {
        cout << "Brand: " << brand << ", Top Speed: " << topSpeed << " km/h" << endl;
    }
};

int main() {
    Car car1("Toyota", 180); // Pass values to the constructor
    Car car2("BMW", 240);    // Different values for another object

    car1.displayInfo();
    car2.displayInfo();

    return 0;
}

Output:

Brand: Toyota, Top Speed: 180 km/h
Brand: BMW, Top Speed: 240 km/h

If you understand the concept of constructor overloading in C++, let’s explore how you can write a parameterized constructor in C++.

Syntax of Parameterized Constructor in C++

You can use a parameterized constructor in C++ in two ways: inside the class and outside the class. In inside the class method, you declare and define the constructor inside the class. The implementation is directly within the class body. This approach keeps everything compact and is useful for small classes.

Here‘s the syntax of inside the class approach.

Syntax:

class ClassName {
public:
    // Declaration and definition inside the class
    ClassName(DataType parameter1, DataType parameter2) {
        // Initialization logic here
    }
};

Code Example:

In the following example, the parameterized constructor is written directly in the Person class body.

class Person {
    string name;
    int age;

public:
    // Parameterized constructor defined inside the class
    Person(string n, int a) {
        name = n;
        age = a;
    }

    void display() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};

The outside-the-class approach declares the constructor in the class and defines it outside. This approach is suitable for larger classes or when you want to organize your code for better readability.

Syntax:

class ClassName {
public:
    // Declaration of parameterized constructor
    ClassName(DataType parameter1, DataType parameter2);
};

// Definition of parameterized constructor outside the class
ClassName::ClassName(DataType parameter1, DataType parameter2) {
    // Initialization logic here
}
Code syntax:

class Person {
    string name;
    int age;

public:
    // Declaration of parameterized constructor
    Person(string n, int a);

    void display() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};

// Definition of parameterized constructor outside the class
Person::Person(string n, int a) {
    name = n;
    age = a;
}

Also Read: 10 Best Computer Programming Courses to Get a Job in 2025

After a basic understanding of syntax, let’s check out the working of a parameterized constructor in C++.

How Parameterized Constructor in C++ Work?

Parameterized constructors allow you to pass arguments to set the initial state of an object. This flexibility will enable you to create objects with different properties without the need for repetitive manual initialization. By combining object creation and initialization in a single step, parameterized constructors improve code efficiency, readability, and maintainability.

Here’s a step-by-step explanation of how parameterized constructors work in C++. 

1. Declaration

You can declare a parameterized constructor in the class by specifying its name (same as the class name) followed by a parameter list. These parameters define the values that the constructor will accept during object creation.

Syntax:

class ClassName {
public:
    ClassName(DataType parameter1, DataType parameter2); // Constructor declaration
};

Code snippet:

class Person {
public:
    Person(string name, int age); // Declares a parameterized constructor
};

2. Definition

The parameterized constructor can be defined either inside or outside the class. If defined outside, the ClassName::ConstructorName syntax associates the definition with the class.

Syntax:

Inside the class:

class ClassName {
public:
    ClassName(DataType parameter1, DataType parameter2) {
        // Initialization logic here
    }
};

Outside the class:

ClassName::ClassName(DataType parameter1, DataType parameter2) {
    // Initialization logic here
}

Code snippet:

class Person {
    string name;
    int age;

public:
    Person(string n, int a); // Constructor declaration

    void display() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};

// Constructor definition outside the class
Person::Person(string n, int a) {
    name = n;
    age = a;
}

3. Object Creation

When you create an object of the class, you pass the required arguments to the constructor. The constructor automatically assigns these values to the object’s data members.

Syntax:

ClassName objectName(parameter1_value, parameter2_value);

Code snippet:

int main() {
    Person person1("Rahul", 25);  // Creates a Person object and initializes it
    person1.display();

    Person person2("Priya", 30);    // Another object with different values
    person2.display();

    return 0;
}

Output:

Name: Rahul, Age: 25
Name: Priya, Age: 30

4. Initialization

A parameterized constructor automates the initialization process by assigning the passed values to the object's data members. In this way, every object is correctly initialized as soon as it is created without needing additional function calls.

Code snippet:

Without parameterized constructor:

person1.setName("Raj");
person1.setAge(25);

With parameterized constructor:

Person person1("Raj", 25);

Also Read: What are the Advantages of Object-Oriented Programming?

In the following section, you can explore different ways of using a parameterized constructor in C++.

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

Parameterized constructors make your programs more robust, efficient, and easier to maintain, especially as the complexity rises. Here’s how you can make your code more efficient and flexible using a parameterized constructor in C++.

1. Constructor Overloading

Parameterized constructors work alongside default constructors and other overloaded constructors, providing different ways to initialize objects based on the context. This flexibility enables you to define constructors with varying parameters to suit different use cases.

Code snippet:

class Car {
public:
    Car() { cout << "Default Car\n"; }            // Default constructor
    Car(string brand, int speed) {               // Parameterized constructor
        cout << brand << " with speed " << speed << " created.\n";
    }
};

Car car1;                     // Calls the default constructor
Car car2("Toyota", 180);      // Calls the parameterized constructor

2. Assigning Different Values to Objects

Parameterized constructors allow each object to start with unique attributes, making it possible to create multiple objects with distinct values concisely.

Code snippet:

class Car {
    string brand;
    int speed;

public:
    Car(string b, int s) {  // Parameterized constructor
        brand = b;
        speed = s;
    }

    void display() {
        cout << "Brand: " << brand << ", Speed: " << speed << " km/h\n";
    }
};

Car car1("Toyota", 180);
Car car2("BMW", 240);

car1.display();
car2.display();

3. Ensuring mandatory initialization of attributes 

Using a parameterized constructor in C++, you can enforce the initialization of essential attributes by requiring specific arguments during object creation. This avoids uninitialized objects, reducing potential runtime errors.

Code snippet:

class Person {
    string name;
    int age;

public:
    Person(string n, int a) {  // Mandatory parameters
        name = n;
        age = a;
    }

    void display() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};

Person person("Alice", 25);  // Ensures name and age are always set
person.display();

4. Supporting polymorphic behavior

Parameterized constructors, used along with inheritance, can contribute to polymorphism by allowing base and derived classes to initialize objects with specific attributes dynamically.

Code snippet:

class Vehicle {
protected:
    int speed;

public:
    Vehicle(int s) : speed(s) {}
    virtual void display() { cout << "Speed: " << speed << " km/h\n"; }
};

class Car : public Vehicle {
    string brand;

public:
    Car(string b, int s) : Vehicle(s), brand(b) {}
    void display() override {
        cout << "Brand: " << brand << ", Speed: " << speed << " km/h\n";
    }
};

Vehicle* v = new Car("Tesla", 200);
v->display();  // Polymorphic behavior

Join upGrad’s free Java Object-Oriented Programming to explore high-paying jobs in emerging technologies.

 

Now that you understand how to use parameterized constructors in C++, let's explore some C++ constructor examples.

Examples of Parameterized Constructor in C++

Understanding parameterized constructors in C++ is easier when you see practical examples of how they are used. Here are some C++ constructor examples.

1. Car information with speed

Objective: 

To create a Car class that stores and displays the car brand and speed using a parameterized constructor.

Code snippet:

#include <iostream>
using namespace std;

class Car {
    string brand;
    int speed;

public:
    // Parameterized constructor
    Car(string b, int s) {
        brand = b;
        speed = s;
    }

    void display() {
        cout << "Car Brand: " << brand << ", Speed: " << speed << " km/h" << endl;
    }
};

int main() {
    Car car1("Maruti Suzuki", 150);  // Initializing with parameters
    car1.display();

    return 0;
}

Explanation:

The Car class has a constructor that takes the car’s brand and speed as arguments. When the object car1 is created, the constructor sets its values to "Maruti Suzuki" and 150.

Flow:

  • The Car class is defined with a parameterized constructor that accepts brand and speed.
  • When car1 is created in main(), the constructor is invoked with the parameters "Maruti Suzuki" and 150.
  • The display() method is called to print the car's information to the console.

Output:

Car Brand: Maruti Suzuki, Speed: 150 km/h

2. Initializing student information

To create a class that stores and displays the information of a student using a parameterized constructor.

Code Snippet:

#include <iostream>
using namespace std;

class Student {
    string name;
    int rollNo;

public:
    // Parameterized constructor
    Student(string n, int r) {
        name = n;
        rollNo = r;
    }

    void display() {
        cout << "Student Name: " << name << ", Roll No: " << rollNo << endl;
    }
};

int main() {
    Student student1("Rahul Kumar", 101);  // Initializing with parameters
    student1.display();

    return 0;
}

Explanation:

The Student class has a parameterized constructor that accepts two parameters—name and rollNo. The constructor initializes these attributes when the object is created.

Flow:

  • The Student class is defined with a parameterized constructor.
  • The constructor initializes the data member's name and rollNo using the arguments passed when the object is created.
  • In the main() function, an object student1 is created and initialized with "Rahul Kumar" and 101.
  • The display() method is called on student1 to print the student's details.

Output:

Student Name: Rahul Kumar, Roll No: 101

3. Calculating the area of a rectangle 

Objective:

Calculate and display the area of a rectangle using a parameterized constructor that accepts the length and breadth.

Code snippet:

#include <iostream>
using namespace std;

class Rectangle {
    int length, breadth;

public:
    // Parameterized constructor
    Rectangle(int l, int b) {
        length = l;
        breadth = b;
    }

    void area() {
        cout << "Area of Rectangle: " << length * breadth << " square units" << endl;
    }
};

int main() {
    Rectangle rect1(10, 5);  // Initializing with length=10 and breadth=5
    rect1.area();

    return 0;
}

Explanation:

The Rectangle class has a constructor that takes the length and breadth as parameters. The area() function calculates the triangle’s area based on these values.

Flow:

  • The Rectangle class is defined with a parameterized constructor that initializes the length and breadth attributes.
  • The rect1 object is created in main() with values 10 and for length and breadth, respectively.
  • The area() method is called on rect1 to compute and display the area of the rectangle.

Output:

Area of Rectangle: 50 square units

4. Employee salary and department

Create an Employee class that stores and displays the name, salary, and department using a parameterized constructor.

Code snippet:

#include <iostream>
using namespace std;

class Employee {
    string name;
    float salary;
    string department;

public:
    // Parameterized constructor
    Employee(string n, float s, string d) {
        name = n;
        salary = s;
        department = d;
    }

    void display() {
        cout << "Employee Name: " << name << ", Salary: " << salary << ", Department: " << department << endl;
    }
};

int main() {
    Employee emp1("Amit Sharma", 50000.50, "IT");  // Initializing with parameters
    emp1.display();

    return 0;
}

Explanation:

The Employee class uses a parameterized constructor to initialize the employee’s namesalary, and department upon creation. The display() function outputs this information.

Flow:

  • The Employee class is defined with a parameterized constructor that accepts the employee's namesalary, and department.
  • The emp1 object is created in main() with values "Amit Sharma"50000.50, and "IT".
  • Emp1 calls the display() method to print the employee's name, salary, and department.

Output:

Employee Name: Amit Sharma, Salary: 50000.5, Department: IT

Also Read: What is Programming Language? Syntax, Top Languages, Example

After going through examples, let’s check how the default constructor differs from parameterized construction in C++.

upGrad’s Exclusive Software and Tech Webinar for you –

SAAS Business – What is So Different?

 

Differences Between Default Constructor and Parameterized Constructor

There are two primary types of constructors in C++: default constructors and parameterized constructors. Both are essential for object initialization, but they differ in how they assign values to the object's attributes and their definition.

A default constructor does not take any parameters and provides default values for the object’s attributes. The compiler automatically generates a default constructor if no constructor is explicitly defined. On the other hand, a parameterized constructor takes one or more parameters and allows the initialization of an object with specific values at the time of its creation.

Do you know how a default constructor and a parameterized constructor differ from each other? Find out in the following table.

Parameters Default Constructor Parameterized Constructor
Initialization  Initializes objects with default values (ex: 0 for integers and nullptr for pointers) Initializes objects with specific values passed as arguments.
Invocation  Automatically invoked when an object is created with no arguments. Explicitly invoked with arguments during object creation.
Use Case Used when no initial values are needed. Used when you need to set specific values for object attributes.
Constructor overloading Cannot be overloaded (since it doesn't take any parameters). Can be overloaded, allowing multiple constructors with different sets of parameters.
Flexibility Less flexible, as it can only assign default values. Highly flexible, as it allows different values at object creation.
Example usage cpp<br>Car car1;  cpp<br>Car car1("Toyota", 180); 
Default Provided by Language Automatically provided by the compiler. Not provided by the compiler.
Typical Implementation Constructor with no parameters. Constructor with one or more parameters.

Also Read: Difference Between Overloading and Overriding

Now that you understand a parameterized constructor in C++, let's explore how to prepare for a career in programming.

How Can upGrad Help You Ace Your Programming Career?

The global job market is witnessing a surge in demand for skilled programmers. In 2024, approximately 40% of recruiters are looking for candidates proficient in programming languages such as Python, Java, and JavaScript.

upGrad’s courses focus on high-paying languages like Java and Python, positioning you for lucrative roles in the industry. These industry-oriented courses ensure that you acquire both theoretical knowledge and practical experience.

Here are some courses offered by upGrad in programming languages.

Do you need help deciding which course to choose for your career as a C++ programmer? Contact upGrad for personalized counseling and valuable insights.

References:

https://www.statista.com/statistics/1296727/programming-languages-demanded-by-recruiters/

Discover our free software development courses designed to enhance your skills and accelerate your career growth in the tech industry.

Dive into our popular software engineering courses and gain the expertise needed to excel in the ever-evolving tech landscape.

Frequently Asked Questions (FAQs)

1. What is a pointer in C++?

In C++, a pointer is a variable that stores the memory address of another variable

2. How to pass an object to the constructor in C++?

To pass an object as an argument to a constructor, write the object name as the argument while calling the function.

3. What are the parameters in C++?

Parameters in C++ are variables that are used to define a function and pass information to it.

4. What is a default parameterized constructor in C++?

A default constructor in C++ is a constructor that either has no parameters or has parameters that have default values.

5. What are the advantages of constructors in C++?

Constructors ensure that objects are initialized with valid values, allocate necessary resources for creating objects, and increase the efficiency of the code.

6. Can a constructor be private in C++?

Yes, a constructor can be private. You have to call it with member functions or friend functions.

7. What are the three types of constructors in C++?

Default, Copy, and Parameterized constructors are the three types of constructors in C++.

8. What is constructor overloading in C++?

The constructor overloading feature in C++ allows a class to have multiple constructors with different parameter lists.

9. What is a dynamic constructor in C++?

A Dynamic constructor enables the allocation of resources and execution of code at runtime.

10. What is a destructor in C++?

A destructor is a member function in C++ that's automatically called when an object is destroyed or goes out of scope.

RELATED PROGRAMS