C++ Constructors C-PLUS-PLUS
- C++ Introduction
- C++ Syntax
- C++ Output (cout <<)
- C++ Comments
- C++ Variables
- C++ User Input
- C++ Data Types
- C++ Operators
- C++ Strings
- C++ Math
- C++ Booleans
- C++ If Else
- C++ Switch
- C++ While Loop
- C++ Do/While Loop
- C++ For Loop
- C++ Break and Continue
- C++ Arrays
- C++ References
- C++ Pointers
- C++ Functions
- C++ Functions Parameters
- C++ Function Overloading
- C++ OOP
- C++ Classes and Objects
- C++ Class Methods
- C++ Constructors
- Destructors in C++
- C++ Access Specifiers
- C++ Encapsulation
- C++ Inheritance
- C++ Polymorphism
- C++ Files
- C++ Exception Handling
C++ Constructors
C++ Constructors
A constructor in C++ is a special method that is automatically called when an object of a class is created. To create a constructor, use the same name as the class, followed by parentheses ().
How constructors are different from a normal member function?
A constructor is different from normal functions in the following ways:
- The constructor has the same name as the class itself
- Constructors don’t have the return type
- A constructor is automatically called when an object is created.
- If we do not specify a constructor, the C++ compiler generates a default constructor for us (expects no parameters and has an empty body).
Example
#include <iostream>
using namespace std;class MyClass { // The Class
public: // Access specifier
MyClass() { // Constructor
cout << "Hello World!";
}
};int main() {
MyClass myObj; // Create an object of MyClass (this will call the constructor)
return 0;
}
Output:
Hello World!
C++ Parameterized Constructors
It is possible to pass arguments to constructors. These arguments help initialize an object when it is created. To create a parameterized constructor, simply add parameters to it the way you would to any other function. When you define the constructor’s body, use the parameters to initialize the object.
Example
#include <iostream>
using
namespace
std;
class
Point {
private
:
int
x, y;
public
:
// Parameterized Constructor
Point(
int
x1,
int
y1)
{
x = x1;
y = y1;
}
int
getX()
{
return
x;
}
int
getY()
{
return
y;
}
};
int
main()
{
// Constructor called
Point p1(10, 15);
// Access values assigned by constructor
cout <<
"Value of p1.x = "
<< p1.getX() <<
", Value of p1.y = "
<< p1.getY();
return
0;
}
Output:
Value of p1.x = 10, Value of p1.y = 15
Uses of Parameterized constructor:
- It is used to initialize the various data elements of different objects with different values when they are created.
- It is used to overload constructors.
Can we have more than one constructor in a class?
Yes, It is called Constructor Overloading.