Title: Chapter 6 Constructors and Destructors ?????????
1Chapter 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
26.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!
3Constructor 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
4Default 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
5Parameterized 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)
6Overloading 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)
7Overloading 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
-
9Constructors 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)
10Constant 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.
116.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
-
14Constructor 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
156.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
-
176.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
18When 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
19Shallow 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
20Shallow Copy Demo
PersonPerson(Person person) id person.id
birthDate person.getBirthDate()
21Deep 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
226.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
23Notes
- 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
24Summary
- 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
25Review Questions