Constructor in C++
Constructor:
Constructor is a special type of member function that is automatically called when an object of the class is created to whom the constructor belongs.
Properties of constructor:
- A constructor initializes an object as soon as it is created.
- Constructor name is same as class name and it doesn't have a return type.
class A
{
public:
A ( ) // constructor of class A
{
// object initialization
}
};
Constructors can be defined either inside the class definition or outside class definition using class name and scope resolution :: operator.
Uses of constructor:
Constructor are Used Because the memory used by Classes can't be released.
But in case of constructor the memory used by the constructor can be freed by using a special member function ,which is known as destructor. This is the basic purpose of constructors in c++.
☝ Make it clear that whether you define a constructor or not a constructor always exist and is called whenever you create an object of the class.
Types of constructor:
Constructors are of three types:- Default Constructor
- Parameterized Constructor
- Copy Constructor
Default Constructors:
Default constructor is the constructor which doesn't take any argument. It has no parameter.
Syntax:
class_name ()
{
// constructor definition
}
Example:
class Demo {
public:
int obj;
Demo (){
obj=10; // object initialization
}
};
int main (){
Demo c;
cout << c.obj;
}
Output:
10
In this case, as soon as the object is created the constructor is called which initializes its data members.
A default constructor is so important for initialization of object members, that even if we do not define a constructor explicitly, the compiler will provide a default constructor implicitly.
Parameterized Constructor :
A constructor is called Parameterized Constructor when it accepts a specific number of parameters. To initialize data members of a class with distinct values.
Example:
#include <iostream>
using namespace std;
class Demo {
public:
int obj;
Demo (int a){
obj=a;
}
};
int main (){
Demo a(4);
Demo b(5);
Demo c(6);
cout << a.obj <<endl;
cout << b.obj <<endl;
cout << c.obj <<endl
return 0;
Output:
4
5
6
Copy Constructor:
These are special type of Constructors which takes an object as argument, and is used to copy values of data members of one object into other object.
Example:
#include<iostream> using namespace std;
class Point
{ private:
int x, y;
public:
Point(int x1, int y1) { x = x1; y = y1; }
// Copy constructor
Point(const Point &p2) {x = p2.x; y = p2.y; }
int getX() { return x; }
int getY() { return y; }
}; int main()
{ Point p1(10, 15); // Normal constructor is called here
Point p2 = p1; // Copy constructor is called here
// Let us access values assigned by constructors
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();
return 0;
} |
Watch a quick editorial here:
Very easy... It help me alot
ReplyDeleteVery helpful information for me
ReplyDelete