Ctors & Dtors Basics
Part of the Object Oriented Programming section of Coddy's C++ journey — lesson 10 of 104.
A constructor is a special method that runs automatically when an object is created. A destructor runs when the object is destroyed.
Default constructor
class Book {
private:
std::string title;
int pages;
public:
Book() {
this->title = "Unknown";
this->pages = 0;
}
};Parameterized constructor
Book(std::string title, int pages) {
this->title = title;
this->pages = pages;
}Constructor overloading — multiple constructors
class Book {
private:
std::string title;
int pages;
public:
Book() {
this->title = "Unknown";
this->pages = 0;
}
Book(std::string title) {
this->title = title;
this->pages = 0;
}
Book(std::string title, int pages) {
this->title = title;
this->pages = pages;
}
};Destructor — runs when object is destroyed
class Book {
public:
~Book() {
std::cout << "Book destroyed" << std::endl;
}
};Creating objects with different constructors
Book book1; // Default constructor
Book book2("Harry Potter"); // One parameter
Book book3("1984", 328); // Two parametersConstructors have the same name as the class with no return type. Destructors use ~ClassName() and are called automatically in reverse order of creation when objects go out of scope.
Challenge
MediumCreate a Product class with three overloaded constructors and a destructor:
- 3-parameter constructor: name, price, stock
- 2-parameter constructor: name, price (stock = 0)
- Default constructor: name = "Unknown", price = 0, stock = 0
- Destructor: prints
"Destroying: <name>"
Cheat sheet
A constructor is a special method that runs automatically when an object is created. A destructor runs when the object is destroyed.
Default constructor — initializes with default values:
class Book {
private:
std::string title;
int pages;
public:
Book() {
this->title = "Unknown";
this->pages = 0;
}
};Parameterized constructor — accepts parameters:
Book(std::string title, int pages) {
this->title = title;
this->pages = pages;
}Constructor overloading — multiple constructors with different parameters:
class Book {
private:
std::string title;
int pages;
public:
Book() {
this->title = "Unknown";
this->pages = 0;
}
Book(std::string title) {
this->title = title;
this->pages = 0;
}
Book(std::string title, int pages) {
this->title = title;
this->pages = pages;
}
};Destructor — runs when object is destroyed, uses ~ClassName():
class Book {
public:
~Book() {
std::cout << "Book destroyed" << std::endl;
}
};Creating objects with different constructors:
Book book1; // Default constructor
Book book2("Harry Potter"); // One parameter
Book book3("1984", 328); // Two parametersConstructors have the same name as the class with no return type. Destructors are called automatically in reverse order of creation when objects go out of scope.
Try it yourself
#include <iostream>
#include "Product.h"
int main() {
std::string name;
int price, stock;
std::getline(std::cin, name);
std::cin >> price >> stock;
Product product1(name, price, stock);
Product product2("Keyboard", 79);
Product product3;
std::cout << "Product 1: " << product1.getName() << " - $" << product1.getPrice() << " (Stock: " << product1.getStock() << ")" << std::endl;
std::cout << "Product 2: " << product2.getName() << " - $" << product2.getPrice() << " (Stock: " << product2.getStock() << ")" << std::endl;
std::cout << "Product 3: " << product3.getName() << " - $" << product3.getPrice() << " (Stock: " << product3.getStock() << ")" << std::endl;
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