13.2.3: Classes and Objects - Constructor and Destructor
- Page ID
- 29115
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)
( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\id}{\mathrm{id}}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\kernel}{\mathrm{null}\,}\)
\( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\)
\( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\)
\( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)
\( \newcommand{\vectorA}[1]{\vec{#1}} % arrow\)
\( \newcommand{\vectorAt}[1]{\vec{\text{#1}}} % arrow\)
\( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vectorC}[1]{\textbf{#1}} \)
\( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)
\( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)
\( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)Constructors
Constructors are special class members which are called by the compiler every time an object of that class is instantiated. Constructors have the same name as the class and may be defined inside or outside the class definition. Constructors are usually used to setup the object that is being created. If you do NOT actually code and call a constructor then C++ will simply create an object.
There are 3 types of constructors:
- Default constructors
- Parametized constructors
- Copy constructors
// C++ program to demonstrate constructors #include <bits/stdc++.h> using namespace std; class Courses { public: int id; //Default Constructor Courses() { cout << "Default Constructor called" << endl; id=-1; } //Parametized Constructor Courses(int x) { cout << "Parametized Constructor called" << endl; id=x; } }; int main() { // obj1 will call Default Constructor Courses courseObj1; cout << "Courses id is: " << courseObj1.id << endl; // obj1 will call Parametized Constructor Courses courseObj2(21); cout << "Courses id is: " << courseObj2.id << endl; return 0; }
In this code we show both the default constructor, which has no arguments, and the parameterized constructor which takes arguments. Notice that the constructor method is simply the same as the name of the class we are constructing. Also, it is valid to have a default constructor with arguments.
The constructor gets called when the instance of a class is created. In our code above, we have the statement: Courses courseObj1; - at this point in our code the constructor method is called and memory is allocated for our object. This is shown in our output where the statement from within the constructor is output PRIOR to the statement in the code.
Default Constructor called Geek id is: -1 Parametrized Constructor called Geek id is: 21
A Copy Constructor is a member function which initializes an object using another object of the same class. A copy constructor has the following general function prototype:
ClassName (const ClassName &old_obj);
Here is an example of the copy constructor.
#include<iostream> using namespace std; class Point { private: int x, y; public: Point(int x1, int y1) { x = x1; y = y1; } // Copy constructor takes the input value Point(const Point &inputPt) { x = inputPt.x; y = inputPt.y; } int getX() { return x; } int getY() { return y; } }; int main() { Point myP1(10, 15); // Normal constructor is called here Point myP2 = myP1; // Copy constructor is called here // Let us access values assigned by constructors cout << "myP1.x = " << myP1.getX() << ", myP1.y = " << myP1.getY() << endl; cout << "myP2.x = " << myP2.getX() << ", myP2.y = " << myP2.getY() << endl; return 0; }
The place we need to pay attention in the above code is where we declare myPt2 - this is where the copy constructor gets called. Our copy constructor simply copies the object variable values from the myPt1 object to the variables in the new myPt2 object. You can see from the output that both of these objects have the same variable values because of this copy. It is allowed to write copy constructors that do whatever you need them to do. The copy constructor is not restricted to simply
myP1.x = 10, myP1.y = 15 myP2.x = 10, myP2.y = 15
Destructors
Destructor is another special member function that is called by the compiler when the scope of the object ends.
// C++ program to explain destructors #include <iostream> using namespace std; class Courses { public: int id; //Definition for Destructor ~Courses() { cout << "Destructor called for id: " << id <<endl; } }; int main() { Courses newObj1; newObj1.id=7; int i = 0; while ( i < 5 ) { Courses newObj2; newObj2.id=i; i++; } // Scope for obj2 ends here return 0; } // Scope for obj1 ends here
Just as we have a constructor, we have destructors that destroy the objects and release the memory back to the system.
One note in the code above is to look at newObj2. It is created within the block of code that is associated with the while loop. As we said when we discussed variable scope - a variable is only available within its block of code, or sub-blocks. So, newObj2 is created within this block, BUT, when we hit the bottom this loop newobj2 goes "out of scope" and the destructor method is called. Each time through the loop newObj2 is created again, and assigned an increasing id (we are incrementing i++). Then finally when the program ends newObj1 is destroyed as well, as you can see in the output below.
Destructor called for id: 0 Destructor called for id: 1 Destructor called for id: 2 Destructor called for id: 3 Destructor called for id: 4 Destructor called for id: 7
Adapted from:
"C++ Classes and Objects" by BabisSarantoglou, Geeks for Geeks is licensed under CC BY-SA 4.0