Constructors in C++
Constructor in C++ is a ‘special’ member function whose task
is to initialize the objects of it’s class. It is 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 value and members of the class.
A constructor is declared and defined as follows :
Constructors don’t have a return type, and the constructor is automatically called when an object is created. If we do not specify a constructor, a C++ compiler generates a default constructor for us (expects no parameters and has an empty body).
There are generally three types of constructors in C++ :
1. DEFAULT
CONSTRUCTORS
2. PARAMETERIZED
CONSTRUCTORS
3. COPY CONSTRUCTORS
Default
Constructors :
Default constructor is the type of constructors in which they take no arguments. It has no parameters. Even, if we do not define any constructor then the compiler creates a default constructor implicitly.
OUTPUT :
10
20
Parameterized
Constructors :
Parameterized constructors are the constructors which take up
arguments. These arguments help objects are
initialize when we create them. 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.
For better understanding look at the code given below :
100
200
We can also have multiple constructor of a single class. This is possible by using Constructor Overloading.
Copy Constructors
:
A copy constructor is
a member function which initializes an object with the help of some other
object of same class.
100
200
100
200
This
is all about constructors, we hope you gained something after giving this a
read. Tell us in comment section if you find anything incorrect in this. And also
drop suggestions regarding the topics you want articles on.
For
this article we took help from a book Object Oriented Programming with C++ by EBalagurusamy.
Thank
You!
Happy
Coding!
No comments:
Post a Comment