C++ Constructors
A constructor is a member function is can be used to initialize data members.
-
It must be public member function.
-
It must be named the same as the class.
-
It must be no return type. Not even void.
-
Constructor is automatically called when an object of the class is created.
-
It is created by parenthesis ().
-
The constructor functions have the same name as that of the class name.
-
Mayor may not have parameters
Syntax– Constructor declaration
Inline:
class Square
{
. . .
public:
Square(int s)
{
side = s;
}. . .
};
|
Declaration outside
the class:
Square(int); //prototype
//in class
Square::Square(int s)
{
side = s;
}
|
Example
Output
Types of constructor
There are three types of constructors are as follows:
- Default Constructor
- Parameter Constructor
- Copy Constructor
1.Default Constructor: Because in C++ Default Constructor, This constructor has no argument. A default constructor is also called a no-argument constructor.
the Default argument is an argument to a function that a programmer is not required to specify.
C++ allows the programmer to specify default arguments that always have, even if one is not specified when calling the function.
For example, in the following function declaration:
2.Parameter Constructor: A parameterized constructor is just one that has parameters specified in it.
For example, in the following function declaration:
3.Copy Constructor
Copy constructor is used declare and initialize an object from another object.
For example, in the following function declaration:
class A
{
A(A &x) // copy constructor.
{
// copyconstructor.
}
}