A constructor is a special member function used to initialize the objects of its class. It is a special because its name is the same as the class name. The constructor is invoked whenever an object of its associated class is created. It is called constructor because it constructs the values of data members of the class.
The constructor function have some special characteristics. These are
- They should be declared in the public section.
- They are invoked automatically when the objects are created
- They do not have return type, even void.
- They have same name as class name.
- We can also pass parameters and call explicitly if necessary.
How to create C++ Constructors
In any programming language, the constructor have the same name as class name and its body. Here is an example constructor of class Rectangle
class Rectangle { private: int length, width; public: Rectangle()// constructor with same name as class name { length=5; width=10; } }
Different types of constructors in C++
There are three types of constructors in C++. The type of constructor used depends on the requirement of the program.
1. Default constructor
2. Parameterized constructor
C++ Default constructor
A constructor which has parameters is called default constructor. It is invoked (called / executed) at he time object creation.
// Cpp program to illustrate the // concept of Constructors using namespace std; class construct { public: int a, b; // Default Constructor construct() { a = 10; b = 20; } }; int main() { // Default constructor called automatically // when the object is created construct c; cout << "a: " << c.a << endl << "b: " << c.b; return 1; }
In the above program the constructor is used to initialize the data members a and b.
C++ Parameterize Constructor
A constructor which have parameters is called Parameterize Constructor. It is used to provide different values to different objects.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 << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY(); return 0; }
0 comments :
Post a Comment
Note: only a member of this blog may post a comment.