Loading lessons...
Constructors & Parameterized Constructors
Constructors & Parameterized Constructors
So far objects have been initialised by calling a function such as init() or setData() after creating them. If the call is forgotten, the object holds garbage. C++ solves this with constructors: special member functions that run automatically when an object is created, so every object starts in a valid state.
1. What a Constructor Is
A constructor is a special member function whose job is to initialise the objects of its class. It is "special" because its name is the same as the class name, and it is invoked automatically whenever an object of the class is created.
class Integer {
int m, n;
public:
Integer(); // constructor declared
};
Integer::Integer() { // constructor defined
m = 0;
n = 0;
}The declaration Integer obj; creates obj and initialises m and n to 0.
Characteristics of constructors
- The constructor has the same name as the class.
- It is invoked automatically when an object is created.
- It should be declared in the public section (otherwise objects cannot be created outside the class).
- It has no return type, not even
void, so it cannot return a value. - It cannot be inherited, though a derived class constructor can call the base class constructor.
- Like other functions, it can have default arguments and can be overloaded.
- It cannot be
virtual,staticorconst. - Its address cannot be taken.
- An object with a constructor (or destructor) cannot be a member of a union.
- Constructors make implicit calls to
newanddeletewhen memory allocation is required.
2. Default Constructor
A constructor that takes no arguments (or whose arguments all have default values) is a default constructor. If a class has no constructor at all, the compiler supplies an implicit default constructor that does nothing special.
#include <iostream>
using namespace std;
class Counter {
int count;
public:
Counter() { // default constructor
count = 0;
cout << "Counter created, count = " << count << endl;
}
void increment() {
count++;
}
int get() {
return count;
}
};
int main() {
Counter c1; // constructor runs here automatically
c1.increment();
c1.increment();
cout << "c1 = " << c1.get() << endl;
Counter c2; // and again for c2
cout << "c2 = " << c2.get() << endl;
return 0;
}Output:
Counter created, count = 0
c1 = 2
Counter created, count = 0
c2 = 03. Parameterized Constructors
A constructor that takes arguments is a parameterized constructor. It lets different objects start with different values. The initial values are passed when the object is created, in one of two ways:
| Way | Syntax |
|---|---|
| Implicit call (shorthand, most common) | Integer int1(0, 100); |
| Explicit call | Integer int1 = Integer(0, 100); |
With a parameterized constructor, Integer int1; no longer compiles unless a default constructor is also defined, because the compiler stops supplying the implicit default constructor once any constructor is declared.
#include <iostream>
using namespace std;
class Point {
int x, y;
public:
Point(int a, int b) { // parameterized constructor
x = a;
y = b;
}
void display() {
cout << "(" << x << ", " << y << ")" << endl;
}
};
int main() {
Point p1(10, 20); // implicit call
Point p2 = Point(30, 40); // explicit call
cout << "p1 = ";
p1.display();
cout << "p2 = ";
p2.display();
// Point p3; // error: no default constructor
return 0;
}Output:
p1 = (10, 20)
p2 = (30, 40)A constructor parameter cannot be of the class's own type by value: A(A a) is illegal. It can be a reference to its own class, A(A& a), which is the copy constructor (Lesson 17).
4. Multiple Constructors (Constructor Overloading)
A class can have more than one constructor, as long as their argument lists differ. This is constructor overloading, and it lets objects be created in several ways.
#include <iostream>
using namespace std;
class Complex {
float real, imag;
public:
Complex() {
real = 0;
imag = 0;
} // no arguments
Complex(float a) {
real = a;
imag = a;
} // one argument
Complex(float r, float i) {
real = r;
imag = i;
} // two arguments
friend Complex sum(Complex c1, Complex c2);
void show() {
cout << real << " + j" << imag << endl;
}
};
Complex sum(Complex c1, Complex c2) {
Complex c3;
c3.real = c1.real + c2.real;
c3.imag = c1.imag + c2.imag;
return c3;
}
int main() {
Complex A(2.7, 3.5); // two-argument constructor
Complex B(1.6); // one-argument constructor
Complex C; // default constructor
C = sum(A, B);
cout << "A = ";
A.show();
cout << "B = ";
B.show();
cout << "C = ";
C.show();
return 0;
}Output:
A = 2.7 + j3.5
B = 1.6 + j1.6
C = 4.3 + j5.15. Constructors with Default Arguments
Constructor arguments can have default values, which often replaces several overloaded constructors with one.
#include <iostream>
using namespace std;
class Account {
int number;
double balance;
float rate;
public:
Account(int n, double b = 0, float r = 0.04f) { // two defaults
number = n;
balance = b;
rate = r;
}
void show() {
cout << "A/c " << number << ": balance " << balance << ", rate " << rate * 100 << "%"
<< endl;
}
};
int main() {
Account a1(101); // balance 0, rate 4%
Account a2(102, 5000); // rate 4%
Account a3(103, 8000, 0.06f);
a1.show();
a2.show();
a3.show();
return 0;
}Output:
A/c 101: balance 0, rate 4%
A/c 102: balance 5000, rate 4%
A/c 103: balance 8000, rate 6%A constructor whose arguments all have defaults, such as A(int x = 0), is also a default constructor. Declaring both A() and A(int x = 0) makes A obj; ambiguous.
6. Dynamic Initialisation of Objects
Initial values can be supplied at run time, for example from user input or a calculation. Overloaded constructors make this flexible. A classic example is a fixed deposit that can be created with an interest rate (float) or a percentage (int).
#include <iostream>
using namespace std;
class FixedDeposit {
long principal;
int years;
float rate;
float returnValue;
public:
FixedDeposit(long p, int y, float r = 0.12); // rate as a fraction
FixedDeposit(long p, int y, int r); // rate as a percentage
void display() {
cout << "Principal " << principal << ", Return " << returnValue << endl;
}
};
FixedDeposit::FixedDeposit(long p, int y, float r) {
principal = p;
years = y;
rate = r;
returnValue = principal;
for (int i = 1; i <= y; i++) {
returnValue = returnValue * (1.0f + r);
}
}
FixedDeposit::FixedDeposit(long p, int y, int r) {
principal = p;
years = y;
rate = float(r) / 100;
returnValue = principal;
for (int i = 1; i <= y; i++) {
returnValue = returnValue * (1.0f + rate);
}
}
int main() {
long p = 10000; // in a real program these could be read with cin
int y = 2;
FixedDeposit fd1(p, y, 10); // int: 10 percent
FixedDeposit fd2(p, y, 0.10f); // float: 0.10
FixedDeposit fd3(p, y); // default 0.12
fd1.display();
fd2.display();
fd3.display();
return 0;
}Output:
Principal 10000, Return 12100
Principal 10000, Return 12100
Principal 10000, Return 125447. Types of Constructors at a Glance
| Type | Example | Purpose |
|---|---|---|
| Default | A() | initialise with fixed values |
| Parameterized | A(int x, int y) | initialise with given values |
| Default arguments | A(int x = 0) | one constructor, several call forms |
| Copy | A(const A& other) | initialise from another object (Lesson 17) |
| Dynamic | uses new inside | allocate memory per object (Lesson 17) |
| Conversion | A(int x) used for A obj = 5; | convert a basic type to the class (Lesson 21) |
Key points to remember
- Constructor: same name as the class, no return type, called automatically when an object is created, usually public.
- Default constructor takes no arguments; the compiler supplies one only if no constructor is declared.
- Parameterized constructor:
Point p(10, 20);(implicit) orPoint p = Point(10, 20);(explicit). - Constructors can be overloaded and can have default arguments;
A()andA(int = 0)together are ambiguous. - Constructors cannot be virtual, static, inherited, or return a value.
📝 IPU End-Term Exam Corner (5-10 Marks)
- Q1. What is a constructor? List its characteristics. Explain the types of constructors with examples. (10 Marks)
- Write: the definition, at least eight characteristics, and the types table, with the
CounterandPointprograms. - Q2. What is a parameterized constructor? Explain the implicit and explicit ways of calling it. (5 Marks)
- Q3. Explain constructor overloading with the
Complexclass example. (5 Marks) - Write: the three constructors, the friend
sum, and the output. - Q4. What are constructors with default arguments? When can they cause ambiguity? (2.5 Marks)
- Q5. What is dynamic initialisation of objects? (2.5 Marks)