Constructors in C++
Constructors in C++
<class-name> ()
{
...
}
<class-name> (list-of-parameters) {
// constructor definition
}
<class-name>: :<class-name>(list-of-parameters) {
// constructor definition
}
Sample Program to perform Constructor within class
#include <iostream>
using namespace std;
// Class definition
class student {
int rno;
char name[50];
double fee;
public:
/*
Here we will define a constructor
inside the same class for which
we are creating it.
*/
student()
{
// Constructor within the class
int main()
{
student s;
/*
constructor gets called automatically
as soon as the object of the class is declared
*/
s.display();
return 0;
}
Output
Enter the RollNo:11
Enter the Name:Aman
Enter the Fee:10111
11 Aman 10111
public:
/*
To define a constructor outside the class,
we need to declare it within the class first.
Then we can define the implementation anywhere.
*/
student();
void display();
};
/*
Here we will define a constructor
outside the class for which
we are creating it.
*/
student::student()
{
// outside definition of constructor
void student::display()
{
cout << endl << rno << "\t" << name << "\t" << fee;
}
// driver code
int main()
{
student s;
/*
constructor gets called automatically
as soon as the object of the class is declared
*/
s.display();
return 0;
}
Output
Enter the RollNo:11
Enter the Name:Aman
Enter the Fee:10111
11 Aman 10111
className() {
// body_of_constructor
2. Parameterized Constructor
className (parameters...)
// body
}
If we want to initialize the data members, we can also use the initializer
list as shown:
3. Copy Constructor
// body_containing_logic
Just like the default constructor, the C++ compiler also provides an
implicit copy constructor if the explicit copy constructor definition is
not present.
The move constructor takes the rvalue reference of the object of the
same class and transfers the ownership of this object to the newly
created object.
Like a copy constructor, the compiler will create a move constructor for
each class that does not have any explicit move constructor.