Intermediate8 min readLesson 24 of 50
Default Constructor
A constructor is a special method that runs automatically when an object is created. It has the same name as the class and no return type.
#include <iostream>
using namespace std;
class Student {
public:
string name;
int grade;
// Default constructor
Student() {
name = "Unknown";
grade = 0;
cout << "Student created!" << endl;
}
};
int main() {
Student s; // Constructor called automatically
cout << s.name << ", Grade: " << s.grade << endl;
return 0;
}
Output:
Student created!
Unknown, Grade: 0
Parameterized Constructor
class Student {
public:
string name;
int grade;
Student(string n, int g) {
name = n;
grade = g;
}
void display() {
cout << name << " — Grade: " << grade << endl;
}
};
int main() {
Student s1("Alice", 95);
Student s2("Bob", 82);
s1.display();
s2.display();
return 0;
}
Output:
Alice — Grade: 95
Bob — Grade: 82
Member Initializer List
A more efficient way to initialize members — required for const and reference members:
class Circle {
public:
const double PI;
double radius;
Circle(double r) : PI(3.14159), radius(r) { }
double area() { return PI * radius * radius; }
};
Circle c(5.0);
cout << c.area(); // 78.54
Exercise
Create a Product class with a parameterized constructor that sets name, price, and quantity. Add a method totalValue() that returns price × quantity.
Show Solution
#include <iostream>
using namespace std;
class Product {
public:
string name;
double price;
int quantity;
Product(string n, double p, int q) : name(n), price(p), quantity(q) { }
double totalValue() { return price * quantity; }
};
int main() {
Product p("Widget", 9.99, 50);
cout << p.name << " total: $" << p.totalValue() << endl;
return 0;
}
Quiz
When is a constructor called?
- A) When a method is invoked
- B) Automatically when an object is created
- C) When the object is destroyed
- D) Only when explicitly called
Answer
B) Constructors run automatically when the object is instantiated.
What is the return type of a constructor?
- A)
void - B) The class type
- C)
int - D) No return type
Answer
D) Constructors have no return type — not even void.
Summary
- Constructors initialize objects when they are created.
- The default constructor takes no arguments.
- Parameterized constructors accept arguments to set initial values.
- Member initializer lists are more efficient and required for const members.