Easy tutorial for C / C ++ - class 4 (default values of constructor and destructor)
- Let's see how to give a constructor's default value in
initialization with a constructor. When declaring a constructor within a class,
you can supply a datatype and an initial value.
- Let's look at an example.
Example Code
#include
<iostream>
#include
<iomanip>
using
namespace std;
class
tClass{
private :
int Na;
int Nb;
public :
tClass(int A = 1, int B = 2);
void prn();
};
tClass::tClass(int
A, int B){
Na = A;
Nb = B;
}
void
tClass::prn(){
cout << " Na = " <<
Na << ", Nb = " << Nb << endl ;
}
int
main() {
tClass x;
cout << " x : " <<
endl ;
x.prn();
cout << endl ;
tClass y(3);
cout << " y : " << endl
;
y.prn();
cout << endl ;
tClass z(4,5);
cout << " z : " << endl
;
z.prn();
return 0;
}
- We created class 'tClass' and declared member variables
'Na, Nb'. We have created a constructor with two integer arguments. At this
time, we gave 1 and 2 as initial values.
- You created object 'x' in main function. In this case,
we created it without arguments. We then called the output function.
- When declaring object 'y', only one argument were
given. ('tClass y (3); ') Let's call the function' prn () 'to check the result.
- Then, when declaring object 'z', two arguments were
given. ('tClass z (4,5); ') Let's call the function' prn () 'to check the
result.
results
:
x :
Na = 1, Nb = 2
y :
Na = 3, Nb = 2
z :
Na = 4, Nb = 5
- For object 'x', you can see that the
initial values of 1 and 2 of the constructor are output.
- For object 'y', only one initial value
(3) is given. At this time, 3 is assigned to the member variable 'Na' and the
member variable 'Nb' is assigned the initial value '2' of the constructor.
- In case of object 'z', initial values
4 and 5 at the time of object creation are assigned to member variables Na and
Nb and output.
Destructor :
- A destructor (as the opposite of a constructor) is a
special member function that is called when an object is destroyed and cleans
up the object.
- The destructor is indicated by a tilde (~) before the
class name. You can not specify a parameter and the data type of the return
value.
ex)
Declaration of constructor : tClass ();
Declaration of destructor : ~ tClass ();
Definition of constructor : tClass :: tClass () {}
Definition of destructor : tClass :: ~ tClass () {}
- The C
++ compiler automatically calls the default destructor even if you do not
explicitly describe the destructor. If you need to do something special when
destroying an object, you should create a destructor and do something special.
ex) If you have been allocated memory space by dynamic memory allocation in the constructor, you need to deallocate memory allocated by the destructor.
No comments:
Post a Comment