C++ Constructor Overloading
In this page:
What is Constructor Overloading?
Constructor overloading means a class defines several constructors, each with a different number or type of parameters, and C++ automatically calls the one matching the arguments used when an object is created.
Example: What is Constructor Overloading?
#include <iostream>
class Box {
public:
int size;
Box() { size = 1; }
Box(int s) { size = s; }
};
int main() {
Box a;
Box b(10);
std::cout << a.size << " " << b.size << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
The Default Constructor
A default constructor takes no parameters and is used when an object is created without any arguments; if a class defines any other constructor, the compiler stops providing this one automatically, and it must be written explicitly if still needed.
Example: The Default Constructor
#include <iostream>
class Box {
public:
int size;
Box() { size = 1; } // used when Box is created with no arguments
};
int main() {
Box b;
std::cout << b.size << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Overloading by Parameter Count
Constructors can be overloaded simply by taking a different number of parameters, letting objects be initialized with as much or as little information as is available at creation time.
Example: Overloading by Parameter Count
#include <iostream>
class Point {
public:
int x, y;
Point(int px) { x = px; y = 0; }
Point(int px, int py) { x = px; y = py; }
};
int main() {
Point p1(5);
Point p2(5, 10);
std::cout << p1.x << "," << p1.y << " " << p2.x << "," << p2.y << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Overloading by Parameter Type
Constructors can also be overloaded by accepting different parameter types, letting an object be constructed from, for example, either an int or a string.
Example: Overloading by Parameter Type
#include <iostream>
#include <string>
class Label {
public:
std::string text;
Label(int number) { text = std::to_string(number); }
Label(std::string s) { text = s; }
};
int main() {
Label a(5);
Label b("Hi");
std::cout << a.text << " " << b.text << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Delegating Constructors
Since C++11, one constructor can delegate to another constructor of the same class using an initializer-list-style call, avoiding duplicated initialization logic across overloads.
Example: Delegating Constructors
#include <iostream>
class Box {
public:
int size;
Box() : Box(1) {} // delegates to the constructor below
Box(int s) { size = s; }
};
int main() {
Box a;
std::cout << a.size << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: