What is a constructor in C++ and what are its types?
A constructor initializes an object. It has the same name as the class and no return type.
- Default: no parameters.
- Parameterized: takes values.
- Copy:
T(const T&), makes an object from another one. - Move:
T(T&&), takes the data of a temporary. - Delegating: calls another constructor of the same class.
#include <iostream>
#include <string>
class P {
public:
P() : P("none", 0) { std::cout << "default\n"; }
P(std::string n, int a) : name(std::move(n)), age(a) { std::cout << "parameterized\n"; }
P(const P& o) : name(o.name), age(o.age) { std::cout << "copy\n"; }
private:
std::string name;
int age;
};
int main() {
P a;
P b("Riya", 21);
P c = b;
}
Output
parameterized
default
parameterized
copy
See Constructors and Destructors.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |