Constructor overloading
- C++ course
- Intermediate
- Lesson 10/116
- 5 min
Learn to define multiple constructors in the same class.
Constructor overloading
A class can have more than one constructor; this is called overloading. Each constructor must have a different parameter list. The compiler picks which constructor to run by looking at the arguments in the call.
Example: class Note { public: Note() { title = "Empty"; } Note(std::string t) { title = t; } std::string title; };. Note a; calls the first, Note b("Task"); calls the second. Both constructors share the name Note but their parameters differ, so they do not clash. This gives flexibility to initialize objects in different ways.
Clashes and ambiguity
In overloading, parameter lists must be clearly different. Otherwise an ambiguity arises and the compiler errors out. Example: with Note(int) and Note(double) defined, the call Note n('A'); can convert to both int and double; the compiler cannot choose.
Be careful with default parameters too. If Note(int x = 0) is defined, Note n; goes to this constructor. If a parameterless Note() is also defined, ambiguity arises. Mixing default parameters with overloading causes confusion.
Practice Add two overloaded constructors to the Note class
Define a Note class. Under public: add std::string title;, Note() { title = "Empty"; } and Note(std::string t) { title = t; }. In main create two instances: one parameterless, one with "Task". Print both title values with std::cout on separate lines.
Starter code
#include <iostream>
#include <string>
// Define the Note class here
int main() {
// Create two Note instances and print their titles
return 0;
}Sample solution
#include <iostream>
#include <string>
class Note {
public:
std::string title;
Note() {
title = "Empty";
}
Note(std::string t) {
title = t;
}
};
int main() {
Note a;
Note b("Task");
std::cout << a.title << std::endl << b.title;
return 0;
}Expected output
Empty Task
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 With Note() and Note(std::string) defined, which does Note b("Task"); call?
Note() { title = "Empty"; }
Note(std::string t) { title = t; }- The Note(std::string t) constructor Correct answer
- The Note() constructor
- Both of them
- A compile error, none is selected
Explanation: The compiler picks the best-matching constructor by parameter type.
2 Call the second constructor
Note note____;
Note note("Task");
Explanation: Note note("Task"); calls the parameterized constructor.
3 Match each call to the constructor it selects
| Term | Meaning |
|---|---|
Note a; |
Note() |
Note b("Task"); |
Note(std::string) |
Note c(7); |
Note(int) |
Note d('A'); |
ambiguity |