that you can call a parent constructor from a
child constructor's initialization list.)
int
main()
{
A obj(3);
obj.show();
return
0;
}
Output:
0 0 3

Member Initialization List
o
There are two ways to initialize the data members of a
class:
n
Inside the body of constructor
n
Through a member initialization list
Word(string s
,
int k = 1){
_str = s;
_frequency = k;
}
Word(string s, int k = 1) :
_frequency(k){
_str = s;
}
32
Initialization list
starts after a colon.

Member Initialization List
o
Member initialization list also works for data members,
which are user-defined class objects.
#include <iostream>
#include "Point2D.h"
using namespace std;
class Line
{
private:
Point2D _p1;
Point2D _p2;
public:
Line(const Point2D& p1, const Point2D& p2)
: _p1(p1), _p2(p2)
{
}
// ...
};
But make sure that the corresponding member constructors exist!
33

Member Initialization List
o
Elaborating on the last remark
in dark red.
#include <iostream>
#include "Point2D.h"
using namespace std;
class Line
{
private:
Point2D
_p1;
Point2D _p2;
public:
Line(const Point2D& p1, const Point2D& p2)
: _p1(p1), _p2(p2)
{
cout << "Line constructed" << endl;
}
// ...
};
34
class
Point2D
{
private
:
double
_x;
double
_y;
public
:
Point2D(
const
Point2D
& p) {
_x
= p.
_x
;
_y
= p.
_y
;
cout
<<
"Point2D constructed"
<<
endl
;
}
// ...
};
Point2D constructed
Point2D constructed
Line constructed
Output:
Here, we are initializing member
objects _p1 and _p2 using the
arguments p1 and p2 when a
Line object is being constructed.
The syntax _p1(p1) is actually
calling the copy constructor of
Point2D --- to copy p1 to _p1. As
said, there is a default copy
constructor doing shallow copy
for every class, but you can also
write your own to customize the
copy construction.

Member Initialization List
o
When should I use
an initialization list to
initialize data
members?
o
We
have to
use an
initialization list to
initialize the following
things:
1.
Constant member
2.
Reference member
class Word
{
private:
const char _language;
string _str;
int _frequency;
public:
Word(string s, int k = 1)
: _language('E'), _frequency(k) {
_str = s;
}
// ...
};
Word.h
35

36

DESTRUCTORS
37

Class Objects Destruction
o
C++ supports a more general mechanism for user-defined
destruction of class objects through
n
Destructor member function
o
A
destructor
is a special member function with the same
name as class:
o
A destructor takes
n
NO ARGUMENTS
n
Has NO RETURN TYPE
(Thus, there is ONLY ONE destructor in
a class.)
<class name>::~<class name>()
38

Class Objects Destruction
#include <iostream>
using namespace std;
class WordType
{
private:
char* _str;
double _frequency;
public:
}
WordType() : _str(NULL),
_frequency(0) { }
WordType(const char* s, int k=1)
: _frequency(k) {
_str = new char[strlen(s) + 1];
strcpy(_str,s);
cout <<
᾿
Type conv. const
῀
<< endl;
}
~WordType() {
if (_str != NULL)
delete [] _str;
cout << "Dest is called" << endl;
}
WordType.h
When destructor will be
called?

