Menu
Coddy logo textTech

Parameterized Constructor

Part of the Object Oriented Programming section of Coddy's C++ journey — lesson 19 of 104.

A parameterized constructor accepts arguments that let you initialize an object with specific values at creation time. Instead of relying on default values, you can customize each object's initial state.

class Player {
    std::string name;
    int health;
    int level;
public:
    Player(std::string n, int h, int lvl) {
        name = n;
        health = h;
        level = lvl;
    }
};

Player hero("Archer", 100, 5);
Player mage("Wizard", 80, 7);

You can define multiple parameterized constructors with different parameter lists. This is called constructor overloading, and the compiler selects the appropriate one based on the arguments you provide.

class Rectangle {
    int width, height;
public:
    Rectangle(int side) {          // Square
        width = height = side;
    }
    
    Rectangle(int w, int h) {      // Rectangle
        width = w;
        height = h;
    }
};

Rectangle square(10);        // Calls first constructor
Rectangle rect(10, 20);      // Calls second constructor

Parameters can have default values, making some arguments optional. This reduces the need for multiple overloaded constructors.

class Enemy {
    std::string type;
    int damage;
public:
    Enemy(std::string t, int d = 10) : type(t), damage(d) {}
};

Enemy goblin("Goblin");       // damage defaults to 10
Enemy dragon("Dragon", 50);   // damage set to 50

Remember from the previous lesson: once you define a parameterized constructor, the compiler no longer generates a default constructor automatically. If you need both, you must define the default constructor explicitly.

challenge icon

Challenge

Easy

Let's build a product inventory system that demonstrates how parameterized constructors let you create objects with specific initial values, and how constructor overloading provides flexibility in object creation.

You'll create two files to organize your code:

  • Product.h: Define a Product class that represents items in an inventory. Your class should have:
    • Private attributes for name (string), price (double), and quantity (integer)
    • A constructor that takes all three parameters (name, price, quantity) to fully initialize a product
    • A constructor that takes only name and price, with quantity defaulting to 1
    • A constructor that takes only a name, with price defaulting to 0.0 and quantity defaulting to 0
    • A display() method that prints the product info in the format: "<name>: "<name>: $<price> (x<quantity>)"lt;price> (x<quantity>)"
    • A getTotalValue() method that returns price multiplied by quantity
  • main.cpp: Demonstrate all three constructors by reading input and creating products in different ways. Read the following from input:
    • First line: a product name, price, and quantity (space-separated)
    • Second line: a product name and price (space-separated)
    • Third line: just a product name
    Create three Product objects using the appropriate constructor for each input, call display() on each one, then print the total value of all three products combined in the format: "Total inventory value: "Total inventory value: $<value>"lt;value>"

For price output, display with one decimal place. For example, if you create a product "Laptop" with price 999.99 and quantity 5, the display should show "Laptop: $999.99 (x5)".

Include your header file in main.cpp using #include "Product.h".

Cheat sheet

A parameterized constructor accepts arguments to initialize an object with specific values at creation time:

class Player {
    std::string name;
    int health;
    int level;
public:
    Player(std::string n, int h, int lvl) {
        name = n;
        health = h;
        level = lvl;
    }
};

Player hero("Archer", 100, 5);

Constructor overloading allows multiple constructors with different parameter lists:

class Rectangle {
    int width, height;
public:
    Rectangle(int side) {          // Square
        width = height = side;
    }
    
    Rectangle(int w, int h) {      // Rectangle
        width = w;
        height = h;
    }
};

Rectangle square(10);        // Calls first constructor
Rectangle rect(10, 20);      // Calls second constructor

Default parameter values make arguments optional:

class Enemy {
    std::string type;
    int damage;
public:
    Enemy(std::string t, int d = 10) : type(t), damage(d) {}
};

Enemy goblin("Goblin");       // damage defaults to 10
Enemy dragon("Dragon", 50);   // damage set to 50

Once you define a parameterized constructor, the compiler no longer generates a default constructor automatically.

Try it yourself

#include <iostream>
#include <iomanip>
#include <string>
#include "Product.h"

using namespace std;

int main() {
    // Read first product: name, price, and quantity
    string name1;
    double price1;
    int quantity1;
    cin >> name1 >> price1 >> quantity1;
    
    // Read second product: name and price
    string name2;
    double price2;
    cin >> name2 >> price2;
    
    // Read third product: just name
    string name3;
    cin >> name3;
    
    // TODO: Create three Product objects using the appropriate constructor for each
    
    // TODO: Call display() on each product
    
    // TODO: Calculate and print total inventory value
    // Format: "Total inventory value: $<value>"
    // Use fixed and setprecision(1) for one decimal place
    
    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming