0
0
C++programming~5 mins

Parameterized constructor in C++

Choose your learning style9 modes available
Introduction

A parameterized constructor helps create objects with specific values right when you make them. It saves time by setting up the object automatically.

When you want to create a car object with a specific color and model right away.
When making a bank account object with an initial balance.
When creating a student object with a name and grade at the start.
Syntax
C++
class ClassName {
public:
    ClassName(type1 param1, type2 param2) {
        // use param1, param2 to set object properties
    }
};
The constructor has the same name as the class.
It takes parameters to set initial values for the object.
Examples
This constructor sets the car's color when you create it.
C++
class Car {
public:
    string color;
    Car(string c) {
        color = c;
    }
};
This constructor sets the x and y coordinates of a point.
C++
class Point {
public:
    int x, y;
    Point(int a, int b) {
        x = a;
        y = b;
    }
};
Sample Program

This program creates a Book object with a title and number of pages using a parameterized constructor. It then prints these details.

C++
#include <iostream>
#include <string>
using namespace std;

class Book {
public:
    string title;
    int pages;

    Book(string t, int p) {
        title = t;
        pages = p;
    }
};

int main() {
    Book myBook("C++ Basics", 150);
    cout << "Title: " << myBook.title << "\n";
    cout << "Pages: " << myBook.pages << "\n";
    return 0;
}
OutputSuccess
Important Notes

If you don't provide a parameterized constructor, C++ uses a default constructor with no parameters.

You can have multiple constructors with different parameters (called constructor overloading).

Summary

Parameterized constructors let you set object values when creating them.

They have the same name as the class and take parameters.

They make your code cleaner and easier to use.