0% found this document useful (0 votes)
7 views28 pages

CS202 Week2

The document discusses constructors, destructors, copy constructors, and assignment operators in C++. Constructors initialize objects and are called when objects are created. Destructors free resources used by objects and are called when objects are destroyed. The default copy constructor and assignment operator may cause problems for classes with dynamic memory, so these should be defined explicitly as needed.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views28 pages

CS202 Week2

The document discusses constructors, destructors, copy constructors, and assignment operators in C++. Constructors initialize objects and are called when objects are created. Destructors free resources used by objects and are called when objects are destroyed. The default copy constructor and assignment operator may cause problems for classes with dynamic memory, so these should be defined explicitly as needed.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

CS202: Programming Systems

Week 2
Constructors & Destructor

10/2021
CS202 – What will be discussed?
o Constructors
o The this pointer
o Destructor
o Member Initialization
o Copy constructor
o Assignment operator

dbtien @ Programming Systems


Constructors
o Constructor is a physical piece of code (in fact, it is
a special type of method) that is used to construct
and initialize objects.
o It is automatically invoked when a new object is
created.
o There is no returned value, even a void.
o A class can have many constructors (overload)
o Name of the constructors must be the same as the
class name.
dbtien @ Programming Systems
Notes on constructors
o If no constructor is implemented, the
compiler will issue a default constructor
o The default construtor:
n No argument
n Invoke other default constructors of data
members if they are objects.
n Doesn’t initialize other data members if they
are not objects.
dbtien @ Programming Systems
Default constructor
o If there is at least one construtor, the default
constructor will not be created by the compiler

class Date
{ int main()
public: {
Date(int iNewDay); Date today; //error
... …
private: return 0;
... }
};

dbtien @ Programming Systems


Other constructors
o They allow users different options to create
a new object
class Date {
public:
Date();
Date(int, int);
Date(int, int, int);

private:
int iDay, iMonth, iYear;
};

dbtien @ Programming Systems


The this pointer
o Check the following lines of code, are they
correct in terms of: syntax? semantics?
useful?
Date::Date(int iDay, int iMonth, int iYear)
{
iDay = iDay;
iMonth = iMonth;
iYear = iYear;
}

Date today(4, 10, 2021);


dbtien @ Programming Systems
The this pointer

today tomorrow nextweek

+ iDay + iDay + iDay


+ iMonth + iMonth + iMonth
+ iYear + iYear + iYear

o How can we know day, month or year of


which object are using?

dbtien @ Programming Systems


The this pointer
o C++ adds an implicit function parameter - the
pointer to the current object instance: this
o this is a constant pointer, you cannot
modify it within a member function.

dbtien @ Programming Systems


The this pointer
Date::Date(int iDay, int iMonth, int iYear)
{
iDay = iDay;
iMonth = iMonth;
iYear = iYear;
}

o Syntax: correct
o Semantic: legal
o Useful: NO!!!
dbtien @ Programming Systems
The code should be
Date::Date(int iDay, int iMonth, int iYear)
{
this->iDay = iDay;
this->iMonth = iMonth;
this->iYear = iYear;
}

dbtien @ Programming Systems


Destructor
o Invoked automatically, when the variable is
removed from memory (e.g. goes out of scope).
o Each class can have at most one destructor
o The destructor name is a name of a class
preceded by a tilde sign (~).
o Destructor, the same as constructor, has no return
type (even void)
o Destructor frees the resources used by the object
(allocated memory, file descriptors, semaphores
etc.)
dbtien @ Programming Systems
Example
class MyArray {
public:
MyArray();
~MyArray() {
n = 0;
delete [] pArr;
pArr = NULL;
}
private:
int n;
int *pArr;
};
dbtien @ Programming Systems
Notes on destructor
o You don’t need to write a destructor if your class
has nothing to clean up.
o If you are using resources, for example dynamic
memory allocation, and you forget to have your
destructor, the program will create the memory
leaking.

dbtien @ Programming Systems


Members Initialization
o Distinguish between Assignment and
Initialization

Date(int iNDay, int iNMonth, int iNYear)


{
iDay = iNDay;
iMonth = iNMonth;
iYear = iNYear;
}

o This is assignment, not Initialization


dbtien @ Programming Systems
Members Initialization
o This is members initialization
class Date {
public:
Date();
Date(int iNDay, int iNMonth, int iNYear)
: iDay(iNDay), iMonth(iNMonth), iYear(iNYear)
{}
~Date();

private:
int iDay, iMonth, iYear;
};

dbtien @ Programming Systems


Mandatory Members Initialization
o Const members
o References
o Sub-objects which require arguments in
constructors
class Test
{
private:
Another& refA; // reference member
const int MAX; // const member
vector arr;
public:
Test(Another& r)dbtien
: @refA(r), MAX(100), arr (MAX) {}
Programming Systems
};
Default copy constructor
o In each class, if there is no copy constructor, a
default copy constructor will be generated. It helps to
create a new object of this class from another object.
For example:

int main()
{
Rectangle a;
Rectangle b(a); // invoke copy constructor
Rectangle c = a; // invoke copy constructor
}

dbtien @ Programming Systems


Default copy constructor (cont.)
o Default copy constructor performs a bitwise
copy from the source to the current object:

source obj destination obj

ptr ptr

a a

b b

dbtien @ Programming Systems


Copy constructor
o Due to the bitwise copy of the default
constructor, it will cause a serious problem
if the copying takes place when the object
has a member pointer with a dynamic
allocated memory.
n Pointers of the source obj and the destination
obj will refer into the same memory

dbtien @ Programming Systems


Copy constructor
o Depending on the members of the class to
decide whether to have a copy constructor
n When having dynamic allocated members

Test::Test(const Test& src)


{
iSize = src.iSize;
ptr = new int [iSize];
for (int i=0; i<iSize; ++i)
ptr[i] = src.ptr[i];
}

dbtien @ Programming Systems


The default assignment operator
o Similar to the default copy constructor, in
each class, if there is no assignment
operator, a default assignment operator will
be generated
o It also has a similar functionality of a
default copy constructor, i.e. doing a
bitwise copy from the source object to the
destination object.

dbtien @ Programming Systems


Assignment operator
o Thus, if there is a pointer member in the
class, an assignment operator should be
defined.
o Note: assignment operator is a bit different
from the copy constructor:
n Clean up the allocated memory that the pointer
member is pointing to before being allocated with
a new memory.
n Remember to check for self-assignment
dbtien @ Programming Systems
Assignment operator

Source object Destination obj

ptr ptr

• Clean up the memory it is pointing to

• Copy the memory to a new place

dbtien @ Programming Systems


For example
Test& Test::operator=(const Test& src)
{
if (this != &src)
{
delete [] ptr;
iSize = src.iSize;
ptr = new int [iSize];
for (int i=0; i<iSize; ++i)
ptr[i] = src.ptr[i];
}
return *this;
}

dbtien @ Programming Systems


Assignment operator (using swap)
o The src is swapped from the this object, and
will be deleted right after the function finishes

Test& Test::operator=(Test src)


{
swap(iSize, src.iSize);
swap(ptr, src.ptr);
return *this;
}
Copy constructor vs Assignment Op
Copy constructor:
o Create an object from scratch
o No need to check for seft-assignment
o No need to free the resource before
copying

dbtien @ Programming Systems


Remember
The 3 following functions often go together:
o Copy constructor
o Assignment operator
o Destructor

dbtien @ Programming Systems

You might also like