TeachMate
My ProgressJoin Session

Constructors

0/2 completed ยท ~0h 5m

All Topics
OOPLearnConstructors
1 / 2

Constructors

beginner
2 min read

A constructor is a special member function that runs automatically when an object is created.

Purpose

  • Initialize member variables
  • Allocate resources
  • Set up the object in a valid state

Syntax

class Person {
    string name;
    int age;
public:
    // Constructor
    Person(string n, int a) : name(n), age(a) {}
};

Types of Constructors

  1. Default: Takes no arguments (Person())
  2. Parameterized: Takes arguments (Person(string n, int a))
  3. Copy: Creates a copy of another object (Person(const Person& other))

Initializer List

  • Preferred way to initialize members
  • More efficient than assignment in the constructor body
  • Required for const and reference members

Constructor Rules

  • Same name as the class
  • No return type (not even void)
  • Called automatically when object is created
  • Can be overloaded (multiple constructors with different parameters)

Key takeaway: A constructor runs automatically when an object is created โ€” use initializer lists for efficient, safe member initialization.

TeachMate - Interactive learning platform for bachelor students

HomeLearnJoin Session|2 Subjects