C++ Constructors
Constructors in C++
A constructor is a special member function with the same name as the class. The constructor doesn’t have a return type. Constructors are used to initialize the objects of their class. Constructors are automatically invoked whenever an object is created.
Characteristics of Constructors in C++
- A constructor should be declared in the public section of the class.
- They are automatically invoked whenever the object is created.
- They cannot return values and do not have return types.
- It can have default arguments.
Example of Using a Constructor
#include <iostream>
using namespace std;
class Employee
{
public:
static int count; //returns number of employees
string eName;
//Constructor
Employee()
{
count++; //increases employee count every time an object is defined
}
void setName(string name)
{
eName = name;
}
static int getCount()
{
return count;
}
};
int Employee::count = 0; //defining the value of count
int main()
{
Employee Harry1;
Employee Harry2;
Employee Harry3;
cout << Employee::getCount() << endl;
}
Parameterized and Default Constructors in C++
Parameterized constructors are those constructors that take one or more parameters. Default constructors are those constructors that take no parameters.
Constructor Overloading in C++
Constructor overloading is a concept similar to function overloading. One class can have multiple constructors with different parameters. At the time of definition of an instance, the constructor, which will match the number and type of arguments, will get executed.
Constructors with Default Arguments in C++
Default arguments of the constructor are those provided in the constructor declaration. If values are not provided when calling the constructor, the constructor uses the default arguments automatically.
class Employee
{
public:
Employee(int a, int b = 9);
};
Copy Constructor in C++
A copy constructor is a type of constructor that creates a copy of another object. If we want one object to resemble another object, we can use a copy constructor. If no copy constructor is written in the program, the compiler will supply its own copy constructor.
class class_name
{
int a;
public:
//copy constructor
class_name(class_name &obj)
{
a = obj.a;
}
};