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 constructorParameters 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 50Remember 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
EasyLet'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 aProductclass that represents items in an inventory. Your class should have:- Private attributes for
name(string),price(double), andquantity(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.0and quantity defaulting to0 - 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
- Private attributes for
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
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 constructorDefault 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 50Once 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;
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesC++ Build & CompilationHeader Files & Source FilesNamespaces & ScopeIntroduction to OOP in C++Classes vs ObjectsThe 'this' PointerMethods (Member Functions)Attributes (Data Members)Ctors & Dtors BasicsRecap - Simple Calculator4Class Properties
Instance vs Static MembersGetters and SettersConst Member FunctionsMutable KeywordStatic Methods and VariablesFriend Functions & ClassesRecap - Bank Account Manager7Inheritance
Basic InheritanceInheritance Access LevelsCtor & Dtor Call OrderMethod OverridingVirtual Functions & VTableMultiple InheritanceVirtual InheritanceRecap - Employee Hierarchy2Memory Management
Stack vs Heap MemoryPointers and ReferencesDynamic Memory (new/delete)Smart Pointers in C++RAII in C++Recap - Dynamic Array Manager5Encapsulation
Access Specifiers in C++Access Specifiers In DepthInformation HidingStruct vs ClassNested & Inner ClassesRecap - Student Records System8Polymorphism
Compile vs Runtime PolymorphFunction OverloadingVirtual Functions RevisitedPure Virtual FunctionsAbstract ClassesInterface Design in C++Dynamic Casting & RTTIRecap - Shape Calculator3Constructors & Destructors
Default ConstructorParameterized ConstructorCopy ConstructorMove ConstructorConstructor Init ListsDelegating ConstructorsDestructor Deep DiveRule of Three / Five / ZeroRecap - String Class6Operator Overloading
Intro to Operator OverloadArithmetic Operator OverloadComparison Operator OverloadStream OperatorsAssignment Operator Overload[] and () Operator OverloadType Conversion OperatorsRecap - Matrix Class9Templates
Function TemplatesClass TemplatesTemplate SpecializationVariadic TemplatesSFINAE & Type Traits BasicsRecap - Generic Container