C++
Constructor overloading
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.
Exercise 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.
Show example 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;
}
Test yourself
-
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
- The Note() constructor
- Both of them
- A compile error, none is selected
Show answer
The Note(std::string t) constructor — The compiler picks the best-matching constructor by parameter type.
-
Call the second constructor
Note note____;
Show answer
Note note("Task");
-
Match each call to the constructor it selects
- Note a;
- Note()
- Note b("Task");
- Note(std::string)
- Note c(7);
- Note(int)
- Note d('A');
- ambiguity
Next lesson: Destructor