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
C++ Classes and Objects
C++ Constructors and Destructors
C++ Access Specifiers and Encapsulation
C++ Inheritance
C++ Polymorphism and Virtual Functions
C++ Abstract Classes and Interfaces
C++ Operator Overloading
Exercises & Assignments
Build a BankAccount class
Calculate areas with polymorphism
Overload operators for a Money class
Interview Questions & Answers
What is the difference between struct and class in C++?
What is a constructor in C++ and what are its types?
What is a destructor in C++?
What is the difference between overloading and overriding in C++?
What is a virtual function in C++?
What is a pure virtual function and an abstract class in C++?
What is the static keyword in C++?