Chapter 6 Constructors and Destructors ????????? - PowerPoint PPT Presentation

1 / 25
About This Presentation
Title:

Chapter 6 Constructors and Destructors ?????????

Description:

Chapter 6 Constructors and Destructors 6.1 Basic Constructors 6.2 Dynamic Initialization of Objects 6.3 Dynamic Constructors – PowerPoint PPT presentation

Number of Views:190
Avg rating:3.0/5.0
Slides: 26
Provided by: educ5460
Category:

less

Transcript and Presenter's Notes

Title: Chapter 6 Constructors and Destructors ?????????


1
Chapter 6 Constructors and Destructors ?????????
  • 6.1 Basic Constructors
  • 6.2 Dynamic Initialization of Objects
  • 6.3 Dynamic Constructors
  • 6.4 Copy Constructors
  • 6.5 Destructors

2
6.1 Simple Constructors
class integer private int m,n public
integer( )
integer integer( ) m0 n0 int
main() integer i
  • A special member function to construct objects
  • Plays the role of initializing objects
  • Exactly the same name as the class
  • Executed automatically by the system, NOT YOU!

3
Constructor is Special
  • Should be declared in pubic section
  • No return type, not even void
  • Make implicit calls to the operators new and
    delete when memory allocation is required.
  • Cant refer their addresses
  • An object with a constructor (or destructor)
    cant be used as a member of a union

4
Default Constructor
  • A special constructor
  • No parameters, empty body
  • Provided by the system, implicitly
  • only if NO explicitly declared constructors

class Circle public double radius
double getArea() return radius
radius 3.14159
5
Parameterized Constructor
class integer int m,n public
integer(int x, int y) integerinteger(int x,
int y) m x n y
integer int1//??????
Call explicitly integer int1
integer(0,100) Call implicitly integer
int1(0,100)
6
Overloading Constructors
  • class integer
  • int m, n
  • public
  • integer() //constructor 1
  • m0 n0
  • integer(int x,int y) //constructor 2
  • ma nb
  • integer(integer i) //constructor 3
  • mi.m ni.n
  • //////////////////////////////////////////
  • integer I1
  • integer I2(20,40)
  • integer I3(I2)

7
Overloading Constructors
  • class complex
  • float x, y
  • public
  • complex() x y 0
  • complex(float a) x y a
  • complex(float real, float imag)
  • x real
  • y imag
  • friend complex sum(complex, complex)
  • friend void show(complex)

complex sum(complex cl, complex c2) complex
c3 c3.x cl.x c2.x c3.y cl.y
c2.y return(c3) void show(complex c)
coutltltc.xltlt" j"ltltc.yltlt"\n"
8
  • int main()
  • complex A(2.7, 3.5)// define initialize
  • complex B(1.6)// define initialize
  • complex C// define
  • C sum(A, B)// sum() is a friend
  • coutltlt"A " show(A)// show() is also
    friend
  • coutltlt"B " show(B)
  • coutltlt"C " show(C)
  • // Another my to give initial values (second
    method)
  • complex P,Q,R// define P, Q and R
  • P complex(2.5,3.9)//initialize P
  • Q complex(1.6,2.5)// initialize Q
  • R sum(P,Q)
  • cout ltlt"\n"
  • coutltlt"P " show(P)
  • coutltlt"Q " show(Q)
  • coutltlt"R " show(R)
  • return 0

9
Constructors with Default Arguments
  • //imag is 0 by default
  • complex( float real, float imag0)
  • x real y imag
  • ////////////////////
  • complex C(5.0)
  • complex C(2.0,3.0)

default constructor AA() default argument
constructor AA(int 0)
10
Constant Objects
const matrix X(m,n)
  • The object is constant
  • Attempt to modify the data fields will generate
    compile-time error.
  • Constant object can only call const member
    functions.

11
6.2 Dynamic Initialization of Objects
  • Initialize the object a runtime
  • Constructor match the input will be invoked
  • Code sample

class Fixed_deposit long int P_amount//
Principal amount int Years// Period of
investment float Rate// Interest rate
float R_value// Return value of amount public
Fixed_deposit() Fixed_deposit(long int
p, int y, float r0.12) Fixed_deposit(long
int p, int y, int r) void display(void)
12
  • Fixed_deposit Fixed_deposit(long int p, int y,
    float r)
  • P_amount p Years y Rate r
  • R_value P_amount
  • for (int i 1 i lt y i)
  • R_value R_value (1.0 r)
  • Fixed_deposit Fixed_deposit(long int p, int y,
    int r)
  • P_amount p Years y Rate r
  • R_value P_amount
  • for (int i1 ilty i)
  • R_value R_value(1.0float(r)/100)
  • void Fixed_deposit display(void)
  • coutltlt"\n"
  • ltlt"Principal Amount "ltlt P_amount ltlt
    "\n"
  • ltlt"Return Value " ltlt R_value ltlt"\n"

13
  • int main()
  • Fixed_deposit FD1, FD2, FD3 // deposits
    created
  • long int p int y float r int R
  • cout ltlt "Enter amount,period,interest rate(in
    percent)\n"
  • cin gtgt p gtgt y gtgt R
  • FD1 Fixed_deposit(p,y,R)
  • cout ltlt "Enter awount,period,interest
    rate(decimal)\n"
  • cin gtgt p gtgt y gtgt r
  • FD2 Fixed_deposit(p,y,r)
  • cout ltlt "Enter amount and period" ltlt "\n"
  • cin gtgt p gtgt y
  • FD3 Fixed_deposit(p,y)
  • cout ltlt "\nDeposit 1" FD1.display()
  • cout ltlt "\nDeposit 2" FD2.display()
  • cout ltlt "\nDeposit 3" FD3.display()
  • return 0

14
Constructor Initializer
class Time public Time(int hr, int min,
int sec) private int hour int
minute int second
class Action public Action()
id 0 private int
id Time time
Action()time(0, 0, 0) id 0
Action(int hr, int min, int sec)
time(hr, min, sec) id 0
(0, 0, 0) //???
time ?
  • To initialize data fields of the class

15
6.3 Dynamic Constructors
  • Dynamic constructor
  • allocate memory while creating object

class String char name int
length public String()// constructor-l
length 0 name new charlength 1
String(char s) // constructor-2
length strlen(s) name new charlength
1 strcpy(name, s)
void display(void)
cout ltlt name ltlt \n
void join(String a, String b)
16
  • void String join(String a, String b)
  • length a.length b.length
  • delete name
  • name new charlength1// dynamic
    allocation
  • strcpy(name, a.name)
  • strcat(name, b.name)
  • int main()
  • char first "Joseph "
  • String namel(first), name2("Louis")
  • String name3("Lagrange"), sl,s2
  • sl.join(namel, name2)
  • s2.join(sl, name3)
  • namel.display() name2.display()
    name3.display()
  • sl.display() s2.display()
  • return 0

17
6.4 Copy Constructor
  • A Special Constructor
  • ClassName(ClassName )
  • To create an object initialized with another
    objects data
  • A default copy constructor is provided by C
  • For example

integer(integer i) integer I2(I1) integer I2
I1 Circle circle1(5) Circle circle2(circle1)
equivalent
18
When Is Copy Constructor Invoked
  • Explicit object initialization
  • Copy of temporary object for parameter
  • Copy of temporary object for return value

X a //Common construction X b a //Copy
construction ? X b(a)
X fun2() X t return
t //Copy construction b fun2( ) //Common
copy
void fun(X para)
fun(a) //a-gtcopy construction-gtpara
19
Shallow Copy vs. Deep Copy
  • Shallow copy
  • The default copy constructor simply copies each
    data field in one object to its counterpart in
    the other object
  • If the field is a pointer to some object, the
    address of the pointer is copied rather than its
    contents

Run
ShallowCopyDemo
20
Shallow Copy Demo
PersonPerson(Person person) id person.id
birthDate person.getBirthDate()
21
Deep Copy -- Customized Copy Constructor
  • Explicitly define copy constructor
  • Allocate new memory for pointers to point

PersonPerson(Person person) id person.id
Date p person.getBirthDate() birthDate
new Date(p)
Person1.cpp
Person1 .h
Run
CustomCopyConstructor
22
6.5 Destructors
  • Invoked to destroy an object
  • The opposite of constructor
  • Like new vs. delete
  • Named as ClassName

Circle() numberOfObjects--
TestCircle6.cpp
Circle6.h
Circle6.cpp
Run
23
Notes
  • No return value, no parameters
  • So, no overloading
  • A default destructor is available if
  • No destructor is explicitly defined
  • A destructor is useful if some resource, e.g.
    memory is allocated dynamically by an object

PersonPerson(int id, int year, int month, int
day) this -gt id id birthDate
new Date(year, month, day)
PersonPerson() delete birthDate
24
Summary
  • Constructors to initialize object
  • Initialize object and allocate memory
  • Special characteristics
  • Overloading
  • Copy constructor
  • Shallow copy vs. deep copy
  • Const object for non-modify
  • Destructor to destroy objects

25
Review Questions
  • Q6.1
  • Q6.9
Write a Comment
User Comments (0)
About PowerShow.com