Você está na página 1de 19

Object Oriented Programming

Lecture #3 Elhanan Borenstein borens@tau.ac.il

copyrights Elhanan Borenstein

Agenda
The Constructor Function Dynamic Allocation of Data Members The Destructor Function The Copy Constructor Function

copyrights Elhanan Borenstein

Constructors & Destructors

copyrights Elhanan Borenstein

The Constructor Function


Motivation
As we all know, when variables are defined, they may initially contain garbage values. The same is true for class data members. Garbage values can cause severe problems:
Reminder: CPoint class Using a variable before it was initialized Using POINTERS before allocating memory!!!

Although Init() or Set() functions can be used, there is no guarantee that they will be called before using the object.

copyrights Elhanan Borenstein

The Constructor Function


Introduction
The Constructor (Ctor) function can solve the problem described in the previous slide. The Constructor function is called automatically when the object is created.

Object creation

Memory Allocation

Ctor Activation

Constructor function can:


Initialize variables Allocate memory Perform any action we wish to take before starting working with the object.
copyrights Elhanan Borenstein

The Constructor Function


Definition
The name of the Constructor function is similar to the name of the class. Ctor functions should (obviously) be defined in the public section. The Constructor function cannot return a value (and its prototype should not define a void return value either).
Why? What if something went wrong? .

copyrights Elhanan Borenstein

The Constructor Function


Examples
Example: CPoint_a
Note: If the Ctor function does not get any arguments, the object creation does not include parentheses.

Example: CPoint_b
Note 1: If the Ctor function does require arguments, the object cannot be created without specifying them. Note 2: Since the Constructor is called when the object is created, arguments should be passed only when allocating the object (and not when defining a pointer to it).

Example: CPoint_both
Just like any other member function, Ctors can be overloaded and have default parameters Beware of ambiguity (can we define default values for all parameters?).
copyrights Elhanan Borenstein

The Constructor Function


A few notes about constructors
When the only available Ctor requires arguments, they must be sent when creating the object. When defining an array of objects: (e.g. CPoint pArray[10];) we cannot pass arguments (why?). Thus, in this case, we will have to create a Ctor that does not require any arguments.
Note: such a Ctor can still initialize variables. Note: CPoint* = new CPoint(3) vs. CPoint* = new CPoint[3];

What happened before we implemented any Ctor?


The default constructor!!!

copyrights Elhanan Borenstein

The Initialization Line


Definition
The object data members can be initialized even before entering the constructor function body using an initialization line. An initialization line guarantees that when we enter the Ctor functions body, the variables are already initialized. Example: CPoint_init Notes:
Even if after the initialization line there is nothing left for the Constructor function to do, it should still be defined (i.e. simply add { } ). The initialization line is considered part of the function and should thus be written where the function is implemented (rather than in the prototype). The order of parameters in the initialized line is not mandatory.
copyrights Elhanan Borenstein

The Initialization Line


Object creation Memory Allocation Ctor Activation

Mandatory initialization line


An initialization line must be used if:
The object includes an object data member that does not have a default constructor class CPoint { int m_x, m_y; public: CPoint(int CPoint() ax, int ay) { m_x = 0; m_y ==0; ax; m_y ay; } }; class CRect() { CPoint P1, P2; public: CRect() { .. } }
copyrights Elhanan Borenstein

The Initialization Line


More Mandatory initialization line
Note:
The Ctor of the object will be called only after all the data members have been created The Ctors of the data members will be activated before the Ctor of the object itself

Example: CRectangle_init An initialization line must be used also if:


Const variables (e.g. const int zero = 0; ) Reference variable

copyrights Elhanan Borenstein

More about Constructors P1 = 3; CPoint


Some special case
equivalent to: CPoint P1(3);

Sending a constructors argument with = Initializing data members with ={,,}

Temp objects

CPoint P1 = {3,4};

Temporary objects can be created by an explicit call to the constructor. CRect R(CPoint(1,2), CPoint(3,4)); The object scope will be only the line it was created in.

Global objects constructor


In C++ the first line which will be activated may be that of a ctor of a global object.
void main() { } CPoint P1 = {3,4};
copyrights Elhanan Borenstein

Dynamic Allocation of Data Members


as stated above, Ctors are especially useful when the object includes pointers data member that should be dynamically allocated. The Ctor can either allocate the member object or set the pointer to NULL. Example: CPolygon Sowhat can still go wrong?
How will we free the allocated memory? What will happen when we copy the object?

copyrights Elhanan Borenstein

The Destructor Function


Motivation
The Destructor function (Dtor) is responsible for any actions we wish to do just before the object is terminated:
Free allocated memory other actions we wish to perform

The Destructor will be activated in the following scenarios:


Local object termination (when exiting the block where it was defined) Deletion of a dynamically allocated object Global object deletion at the end of the application

copyrights Elhanan Borenstein

The Destructor Function


Definition
The name of the Destructor function is similar to the name of the class with the prefix ~. Dtor functions should (obviously) be defined as public. Example: CPolygon A destructor cannot return a value and doesnt get any arguments. It cannot be overloaded either. WHY? Object creation Object Deletion Memory Allocation (and
embedded objects ctors)

Ctor Activation Dtor Activation


copyrights Elhanan Borenstein

Memory Release (and


embedded objects dtors)

The Copy Constructor (CC) Function


Motivation
As we saw in the last lecture, when copying one object to the other, all data members are copied as is. If the object includes data members that are pointers, we will get dual pointing:
Changing the data member in one object may change the data member in the copied object We may try to free the same allocated memory twice!!!

There are cases when we wish to modify additional data members when an object is copied. (EXAMPLE?) We can implement a Copy Constructor which will properly copy an object!!!

copyrights Elhanan Borenstein

The Copy Constructor (CC) Function


Definition
A copy constructor is simply defined as a constructor that gets the same type of object (ByRef) as an argument. Example: CString Notes:
The Default Copy Constructor. Using private Copy Constructor
} Class MyClass { var1, var2, var3 MyClass(const MyClass& a) : var1(a.var1),var2(a.var2), var3(a.var3)

The only issue we still have to solve is object assignment


CPoint P1(P2);

Note:

or

CPoint P3 = P4;

CPoint P1; vs. P1 = P2;


copyrights Elhanan Borenstein

ByVal Objects
Objects as Arguments
As we recall from the previous lecture, we will always prefer to pass argument objects ByRef rather than ByVal However, if we do pass the argument ByVal, the Copy Constructor will be used.

Return Values
We may still want to return an object as the function return value ByVal. Why? Once again, the Copy Constructor will be used. What will happen if we will try to pass the object to the CC by value?

copyrights Elhanan Borenstein

Questions?

copyrights Elhanan Borenstein

Você também pode gostar