5th Class Tuesday, october 12 CSI2172A - PowerPoint PPT Presentation

1 / 24
About This Presentation
Title:

5th Class Tuesday, october 12 CSI2172A

Description:

Car c2 = c1; ... second example in the same shows a case where the assignment operator ... Car c2 = c1; // copy constructor is invoked. c2 = c1; // assignment operator ... – PowerPoint PPT presentation

Number of Views:21
Avg rating:3.0/5.0
Slides: 25
Provided by: park183
Category:

less

Transcript and Presenter's Notes

Title: 5th Class Tuesday, october 12 CSI2172A


1
5th Class (Tuesday, october 12)CSI2172A
2
The Constructor (I)
  • A constructor is a public method that
  • Has the same name of its class.
  • Initializes the attributes of an object when
    created.
  • Does not have a return type (not even void).
  • Automatically executed when creating an instance
    of a class.
  • Can be omitted.

3
  • A default constructor
  • Defined by the user and takes no arguments.
  • Automatically created by the compiler only when
    no constructor is defined. The automatic
    constructor does
  • nothing, like a dummy function.
  • Note A class without a default constructor
    cannot be used to instantiate objects when the
    appropriate list of parameters is not specified.

The Constructor (II)
class alpha double d public
alpha(double dd) d dd . . alpha a //
illegal declaration
4
The Constructor (III)
  • To declare an array of objects, the corresponding
    class must have a default constructor, which
    would be called for all the elements of the
    array.
  • Car A10
  • //initiates 10 calls for the default constructor
    Car()
  • Note Constructors can have arguments with
    default values, like any other function.

class alpha double d public
alpha(double dd) d dd . . alpha list7
/ illegal No default constructor is defined/
5
The Constructor (IV)
  • Dynamic allocation of an object using the
    operator new invokes a call for the corresponding
    constructor.
  • Car C new Car(...)

6
The Constructor (V)
  • If a constructor takes one single parameter, or
    several ones where all have default values but
    not the first, it can be called by using the
    equal sign followed by the value of the
    single parameter
  • alpha alp 1.2
  • // invokes alphaalpha(1.2)
  • Given a function fn(alpha alp), the following
    calls are legal
  • fn( alpha(5.9) )
  • fn(5.9) // equivalent to fn(alpha(5.9))
  • In this case, the appropriate constructor gets
    called when entering the function, (and the
    destructor when exiting).

7
The Constructor (VI)
  • Similarly, an array of objects can be
    initialized
  • alpha alpList4 1.2, 2, 0.7, -9.9
  • In this example, we had to specify the initial
    values for all elements of the array since there
    is no default constructor in the class alpha. If
    a default constructor is present, we could have
    skipped some or all elements.

8
The Constructor (VII)
class beta private int a public
beta(int) int get_a() betabeta
(int i) a i coutltlt Calling
Constructor beta(int i)" int get_a()
return a int fn(beta abc) return
abc.get_a() int main() return fn(1) //
return 1
  • Based on what we have seen in the previous
    slides, the following example is valid

9
The Constructor (VIII)
  • Function parameters of any class type can be
    assigned default values. The default value in
    this case is introduced using the corresponding
    constructor.
  • void f1(Example ex Example() )
  • void f2(Example ex Example(1, 1) )
  • void f3(alpha alp 0)

10
The Constructor (IX)
  • A copy constructor is a special constructor that
    takes one argument, which is a reference to an
    object of the same class type
  • PointPoint(const Point p)
  • Every class should have a copy constructor that
    handles the copying of the objects content,
    field by field, to another object. If it is not
    defined by the user, the compiler creates one
    automatically.
  • A copy constructor gets invoked when
  • a function returns an object
  • an object is passed by value to a function

11
  • class Example
  • public
  • Example ()
  • // default constructor
  • Example (int i, int j)
  • // an other constructor
  • Example (const Example c)
  • // copy constructor
  • Example c1
  • // calling the default constructor
  • Example c2 c1

12
The Copy Constructor ()
  • The copy constructor gets called during object
    initializations (as any regular constructor)
  • Car c2 c1
  • When simply assigning the value of an object to
    another (previously created) using the equal sign
    , the copy constructor is not invoked. However,
    the assignment operator function is called to
    handle the copying of data members field by
    field.
  • c2 c1

13
The Copy Constructor ()
  • The first example in the previous slide shows a
    scenario where the copy constructor function is
    called. The second example in the same slide
    shows a case where the assignment operator
    function is invoked.
  • Car c2 c1 // copy constructor is invoked
  • c2 c1 // assignment operator function is
    invoked
  • By default, both functions perform the same task
    of copying the content of one object to another
    of the same class type.
  • If you specify your own copy constructor, you
    might need to redefine the assignment operator
    function as well. This is often required to
    maintain the same behaviour in both functions.

14
class Cls private int a // ? Pay
Attention public Cls() Cls() Cls
Cls() printf("\n --gt In ClsCls()\n") a
new int10 // ? Pay Attention for(int i0
ilt10i)aii ClsCls() printf("\n
--gt In Cls Cls()\n") delete a a
(int)0 // ? Pay Attention void fn(Cls
Inst)// ? Pay Attention printf("\n --gt In
fn(Cls)\n")
The Copy Constructor ()
  • What is the purpose of a copy constructor?
  • What does it achieve?

15
The Copy Constructor ()
Using the class Cls and functions defined in the
previous slide
int main() Cls obj
fn(obj)
copy of obj
16
The Copy Constructor ()
  • Problem We got 2 objects who share the same
    memory resource by referencing it with internal
    pointers. What happens when one of them frees the
    allocated memory using delete, while the other is
    still referencing it? The other object will be
    containing a dangling pointer. In our example,
    when the function fn returns, the destructor Cls
    is called and hence, the array is de-allocated
    leaving the original object obj with a dangling
    pointer.
  • Solution Use copy constructor to force a deep
    copy between objects. With a deep copy, all
    memory resources get duplicated for every object.
    Note that the default copy constructor performs a
    shallow copy as seen in the previous example.

17
The Copy Constructor ()
  • Implementing a copy constructor for the class
    Cls, to force a deep copy

class Cls private int a // ? Pay
Attention public Cls() Cls(const Cls)
// ? Pay Attention Cls() ClsCls(const
Cls b) a new int10 // ? Pay
Attention for(int i0 ilt10i) aib.ai
// ? Pay Attention
18
The Copy Constructor ()
Back to our previous graphic, using our copy
constructor this time
int main() Cls obj
fn(obj)
copy of obj
Memory Allocation For an Identical Copy of The
array
19
The Destructor (I)
  • A destructor is a public method that
  • Has the same name of its class, preceded by the
    symbol
  • Gets invoked by an object, local to a block,
    when the block terminates its operation, or when
    the object is destroyed using delete.
  • Would include instructions to free all memory
    resources that were previously allocated to the
    objects data members.
  • Has no return value, and takes no arguments at
    all. It means that we cannot have multiple
    destructors per class.

20
The destructor (II)
  • In general, the role of a destructor is to
    release reserved resources after the object gets
    destroyed. In addition to freeing memory
    resources, it can also include file management
    works, such as closing opened files, etc.
  • If no destructor is specified in a class, the
    compiler uses a default destructor that basically
    does nothing, like a dummy function.

21
new /delete with constructors/destructors
  • The operator new reserves the needed memory
    space for an object in the heap, and invokes a
    constructor.
  • The operator delete invokes the destructor
    first, then frees the reserved memory space.
  • Since a class can have multiple constructors,
    new invokes the appropriate constructor by
    matching the parameter lists.
  • Example xpe1 new Example(1, 2)
  • // Calls the second constructor of the class
    Example
  • Example xpe2 new Example
  • // Calls the first constructor
  • Example xpe3 new Example(c1)
  • // Calls the copy constructor

22
new /delete with constructors/destructors
  • When no parameter is specified, the default
    constructor is invoked. If the default
    constructor does not exist the compiler returns
    an error.
  • It is possible to create arrays of objects with
    the operator new. In this case, the default
    constructor gets called. There is no other way of
    initializing a dynamic array. Note that in a
    previous slide, we saw alternative ways of
    initializing a static array during declaration.

23
new /delete with constructors/destructors
  • Some issues with the array of objects
  • Example exp new Example10
  • ...
  • delete exp // incorrect
  • Since the compiler sees exp as a pointer, it
    calls the destructor of the object referenced by
    exp. In this case, it is only the first element
    of the array. To force the compiler to destroy
    all elements, we need to specify the number of
    elements to be destroyed by the operator delete.
  • Example exp new Example10
  • ...
  • delete10 exp

24
class student private char name
public student operator(const
student) student studentoperator(const
student s) if (s this) return this
delete name name new
charstrlen(s.name) 1 strcpy(name,s.name)
return this
The Assignment Operator
  • The assignment operator represents a public
    method used to assign the value of one object to
    another of the same class type.
  • An assignment operator can be overloaded, similar
    to the case of a copy constructor. That is
    essential when a deep copy (assignment) is
    needed.
  • It performs the same task of a copy constructor
    with one major difference.
  • The copy constructor starts from a raw memory
    location and copy all members to that location.
  • The assignment operator copies the data members
    to their matching members in another existing
    object.
  • student operator(const student)
Write a Comment
User Comments (0)
About PowerShow.com