KEMBAR78
_Constructor in Object Oriented Programming | PPTX
Constructors and Destructors
Department of Computer Science & IT,
The University of Lahore
Interface vs Implementation
• Separating interface from implementation
–Makes it easier to modify programs
–Header files
• Contains class definitions and function prototypes
–Source-code files
• Contains member function definitions
1 // Fig. 6.5: time1.h
2 // Declaration of the Time class.
3 // Member functions are defined in time1.cpp
4
5 // prevent multiple inclusions of header file
6 #ifndef TIME1_H
7 #define TIME1_H
8
9 // Time abstract data type definition
10 class Time {
11 public:
12 Time(); // constructor
13 void setTime( int, int, int ); // set hour, minute, second
14 void printMilitary(); // print military time format
15 void printStandard(); // print standard time format
16 private:
17 int hour; // 0 - 23
18 int minute; // 0 - 59
19 int second; // 0 - 59
20 };
21
22 #endif
If time1.h (TIME1_H) is not defined (#ifndef)
then it is loaded (#define TIME1_H). If TIME1_H
is already defined, then everything up to #endif is
ignored.
This prevents loading a header file multiple times.
Dot ( . ) replaced with underscore ( _ ) in file name.
23 // Fig. 6.5: time1.cpp
24 // Member function definitions for Time class.
25 #include <iostream>
26
27 using std::cout;
28
29 #include "time1.h"
30
31 // Time constructor initializes each data member to zero.
32 // Ensures all Time objects start in a consistent state.
33 Time::Time() { hour = minute = second = 0; }
34
35 // Set a new Time value using military time. Perform validity
36 // checks on the data values. Set invalid values to zero.
37 void Time::setTime( int h, int m, int s )
38 {
39 hour = ( h >= 0 && h < 24 ) ? h : 0;
40 minute = ( m >= 0 && m < 60 ) ? m : 0;
41 second = ( s >= 0 && s < 60 ) ? s : 0;
42 }
43
44 // Print Time in military format
45 void Time::printMilitary()
46 {
47 cout << ( hour < 10 ? "0" : "" ) << hour << ":"
48 << ( minute < 10 ? "0" : "" ) << minute;
49 }
50
51 // Print time in standard format
52 void Time::printStandard()
53 {
54 cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 )
55 << ":" << ( minute < 10 ? "0" : "" ) << minute
56 << ":" << ( second < 10 ? "0" : "" ) << second
57 << ( hour < 12 ? " AM" : " PM" );
58 }
Source file uses #include to load the
header file
Source file contains
function definitions
Constructors
 A constructor is a special function used to create an object.
Constructor has exactly the same name as the defining class
 Constructors can be overloaded (i.e., multiple constructors
with different signatures) [Purpose: making it easy to
construct objects with different initial data values).
 A class may be declared without constructors. In this case, a
no-argument constructor with an empty body is implicitly
declared in the class known as default constructor
 Note: Default constructor is provided automatically only if no
constructors are explicitly declared in the class.
Constructors’ Properties
 must have the same name as the class itself.
 do not have a return type—not even void.
 play the role of initializing objects.
Constructors and Destructors
– Constructor is a function in every class which is
called when class creates its object
• Basically it helps in initializing data members of the
class
• A class may have multiple constructors
– Destructors is a function in every class which is
called when the object of a class is destroyed
• The main purpose of destructor is to remove
dynamic memories etc.
10 // Time abstract data type definition
11 class Time {
12 public:
13 Time( int = 0, int = 0, int = 0 ); // default constructor
14 void setTime( int, int, int ); // set hour, minute, second
15 void printMilitary(); // print military time format
16 void printStandard(); // print standard time format
17 private:
18 int hour; // 0 - 23
19 int minute; // 0 - 59
20 int second; // 0 - 59
21 };
22
23 #endif
Default Parameters in Constructor
Initializing Objects
70
71 int main()
72 {
73 Time t1, // all arguments defaulted
74 t2(2), // minute and second defaulted
75 t3(21, 34), // second defaulted
76 t4(12, 25, 42), // all values specified
77 t5(27, 74, 99); // all bad values specified
78
79 cout << "Constructed with:n"
80 << "all arguments defaulted:n ";
81 t1.printMilitary();
82 cout << "n ";
83 t1.printStandard();
84
85 cout << "nhour specified; minute and second defaulted:"
86 << "n ";
87 t2.printMilitary();
88 cout << "n ";
89 t2.printStandard();
90
91 cout << "nhour and minute specified; second defaulted:"
92 << "n ";
93 t3.printMilitary();
Same constructor, used in overloaded style
OUTPUT
Constructed with:
all arguments defaulted:
00:00
12:00:00 AM
hour specified; minute and second defaulted:
02:00
2:00:00 AM
hour and minute specified; second defaulted:
21:34
9:34:00 PM
hour, minute, and second specified:
12:25
12:25:42 PM
all invalid values specified:
00:00
12:00:00 AM
When only hour is
specified, minute and
second are set to their
default values of 0.
94 cout << "n ";
95 t3.printStandard();
96
97 cout << "nhour, minute, and second specified:"
98 << "n ";
99 t4.printMilitary();
100 cout << "n ";
101 t4.printStandard();
102
103 cout << "nall invalid values specified:"
104 << "n ";
105 t5.printMilitary();
106 cout << "n ";
107 t5.printStandard();
108 cout << endl;
109
110 return 0;
111 }
Using Destructors
• Destructors
– Are member function of class
– Perform termination housekeeping before the system reclaims the object’s
memory
– Name is tilde (~) followed by the class name (i.e., ~Time)
– Receives no parameters, returns no value
– One destructor per class (no overloading)
– Destructors cannot be declared const, static
– A destructor can be declared virtual or pure virtual
When Constructors and Destructors Are Called
Constructors and destructors called automatically
– Order depends on scope of objects
1. Global scope objects
– Constructors called before any other function (including main)
– Destructors called when main terminates (or exit function
called)
– Destructors not called if program terminates with abort
2. Automatic local objects
– Constructors called when objects are defined
– Destructors called when objects leave scope
– Destructors not called if the program ends with exit or
abort
7 class CreateAndDestroy {
8 public:
9 CreateAndDestroy( int ); // constructor
10 ~CreateAndDestroy(); // destructor
11 private:
12 int data;
13 };
14
15 #endif
24
25 CreateAndDestroy::CreateAndDestroy( int value )
26 {
27 data = value;
28 cout << "Object " << data << " constructor";
29 }
30
31 CreateAndDestroy::~CreateAndDestroy()
32 { cout << "Object " << data << " destructor " << endl; }
Constructor and Destructor
changed to print when they are
called.
42
43 void create( void ); // prototype
44
45 CreateAndDestroy first( 1 ); // global object
46
47 int main()
48 {
49 cout << " (global created before main)" << endl;
50
51 CreateAndDestroy second( 2 ); // local object
52 cout << " (local automatic in main)" << endl;
53
54 static CreateAndDestroy third( 3 ); // local object
55 cout << " (local static in main)" << endl;
56
57 create(); // call function to create objects
58
59 CreateAndDestroy fourth( 4 ); // local object
60 cout << " (local automatic in main)" << endl;
61 return 0;
62 }
63
64 // Function to create objects
65 void create( void )
66 {
67 CreateAndDestroy fifth( 5 );
68 cout << " (local automatic in create)" << endl;
69
70 static CreateAndDestroy sixth( 6 );
71 cout << " (local static in create)" << endl;
72
73 CreateAndDestroy seventh( 7 );
74 cout << " (local automatic in create)" << endl;
75 }
OUTPUT
Object 1 constructor (global created before main)
Object 2 constructor (local automatic in main)
Object 3 constructor (local static in main)
Object 5 constructor (local automatic in create)
Object 6 constructor (local static in create)
Object 7 constructor (local automatic in create)
Object 7 destructor
Object 5 destructor
Object 4 constructor (local automatic in main)
Object 4 destructor
Object 2 destructor
Object 6 destructor
Object 3 destructor
Object 1 destructor
Notice how the order of the
constructor and destructor call
depends on the types of variables
(automatic, global and static)
they are associated with.
Static objects are declared with the keyword static. They are initialized only
once and stored in the static storage area. The static objects are only
destroyed when the program terminates i.e. they live until program termination
When do Constructors Get Called?
• Class object creation time
• Dynamically allocated object
• Class argument passed by value
• Class object returned by value
• Object Array element (created)
What Constructors Do
• Help in initializing: class data members
Employee( ) { id = 0; }
• Allocate memory for dynamic members
Employee() { char* nameptr = new char[20];}
• Allocate any needed resources
– Such as to open files, etc.
Constructing Arrays of Objects
Complex c_arr[10];
Date date_arr[20];
Issue: There is no way to call argument-based
constructors (non-default) for array members
Arrays of Objects and Non-Default Constructors
• Trick: declare an array of pointer to objects
• Allocate and initialize each object in a loop
Date *dates[31];
for (int day = 0; day < 31; ++day)
{
dates[day] = new Date(3, day, 2020);
}
Default Member-wise Assignment
• Assignment operator (=) can be used to assign an
object to another object of the same type.
• Member-wise assignment: each data member of the
object on the right of the assignment operator is
assigned individually to the same data member in
the object on the left

_Constructor in Object Oriented Programming
_Constructor in Object Oriented Programming

_Constructor in Object Oriented Programming

  • 1.
    Constructors and Destructors Departmentof Computer Science & IT, The University of Lahore
  • 2.
    Interface vs Implementation •Separating interface from implementation –Makes it easier to modify programs –Header files • Contains class definitions and function prototypes –Source-code files • Contains member function definitions
  • 3.
    1 // Fig.6.5: time1.h 2 // Declaration of the Time class. 3 // Member functions are defined in time1.cpp 4 5 // prevent multiple inclusions of header file 6 #ifndef TIME1_H 7 #define TIME1_H 8 9 // Time abstract data type definition 10 class Time { 11 public: 12 Time(); // constructor 13 void setTime( int, int, int ); // set hour, minute, second 14 void printMilitary(); // print military time format 15 void printStandard(); // print standard time format 16 private: 17 int hour; // 0 - 23 18 int minute; // 0 - 59 19 int second; // 0 - 59 20 }; 21 22 #endif If time1.h (TIME1_H) is not defined (#ifndef) then it is loaded (#define TIME1_H). If TIME1_H is already defined, then everything up to #endif is ignored. This prevents loading a header file multiple times. Dot ( . ) replaced with underscore ( _ ) in file name.
  • 4.
    23 // Fig.6.5: time1.cpp 24 // Member function definitions for Time class. 25 #include <iostream> 26 27 using std::cout; 28 29 #include "time1.h" 30 31 // Time constructor initializes each data member to zero. 32 // Ensures all Time objects start in a consistent state. 33 Time::Time() { hour = minute = second = 0; } 34 35 // Set a new Time value using military time. Perform validity 36 // checks on the data values. Set invalid values to zero. 37 void Time::setTime( int h, int m, int s ) 38 { 39 hour = ( h >= 0 && h < 24 ) ? h : 0; 40 minute = ( m >= 0 && m < 60 ) ? m : 0; 41 second = ( s >= 0 && s < 60 ) ? s : 0; 42 } 43 44 // Print Time in military format 45 void Time::printMilitary() 46 { 47 cout << ( hour < 10 ? "0" : "" ) << hour << ":" 48 << ( minute < 10 ? "0" : "" ) << minute; 49 } 50 51 // Print time in standard format 52 void Time::printStandard() 53 { 54 cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ) 55 << ":" << ( minute < 10 ? "0" : "" ) << minute 56 << ":" << ( second < 10 ? "0" : "" ) << second 57 << ( hour < 12 ? " AM" : " PM" ); 58 } Source file uses #include to load the header file Source file contains function definitions
  • 5.
    Constructors  A constructoris a special function used to create an object. Constructor has exactly the same name as the defining class  Constructors can be overloaded (i.e., multiple constructors with different signatures) [Purpose: making it easy to construct objects with different initial data values).  A class may be declared without constructors. In this case, a no-argument constructor with an empty body is implicitly declared in the class known as default constructor  Note: Default constructor is provided automatically only if no constructors are explicitly declared in the class.
  • 6.
    Constructors’ Properties  musthave the same name as the class itself.  do not have a return type—not even void.  play the role of initializing objects.
  • 7.
    Constructors and Destructors –Constructor is a function in every class which is called when class creates its object • Basically it helps in initializing data members of the class • A class may have multiple constructors – Destructors is a function in every class which is called when the object of a class is destroyed • The main purpose of destructor is to remove dynamic memories etc.
  • 8.
    10 // Timeabstract data type definition 11 class Time { 12 public: 13 Time( int = 0, int = 0, int = 0 ); // default constructor 14 void setTime( int, int, int ); // set hour, minute, second 15 void printMilitary(); // print military time format 16 void printStandard(); // print standard time format 17 private: 18 int hour; // 0 - 23 19 int minute; // 0 - 59 20 int second; // 0 - 59 21 }; 22 23 #endif Default Parameters in Constructor Initializing Objects
  • 9.
    70 71 int main() 72{ 73 Time t1, // all arguments defaulted 74 t2(2), // minute and second defaulted 75 t3(21, 34), // second defaulted 76 t4(12, 25, 42), // all values specified 77 t5(27, 74, 99); // all bad values specified 78 79 cout << "Constructed with:n" 80 << "all arguments defaulted:n "; 81 t1.printMilitary(); 82 cout << "n "; 83 t1.printStandard(); 84 85 cout << "nhour specified; minute and second defaulted:" 86 << "n "; 87 t2.printMilitary(); 88 cout << "n "; 89 t2.printStandard(); 90 91 cout << "nhour and minute specified; second defaulted:" 92 << "n "; 93 t3.printMilitary(); Same constructor, used in overloaded style
  • 10.
    OUTPUT Constructed with: all argumentsdefaulted: 00:00 12:00:00 AM hour specified; minute and second defaulted: 02:00 2:00:00 AM hour and minute specified; second defaulted: 21:34 9:34:00 PM hour, minute, and second specified: 12:25 12:25:42 PM all invalid values specified: 00:00 12:00:00 AM When only hour is specified, minute and second are set to their default values of 0. 94 cout << "n "; 95 t3.printStandard(); 96 97 cout << "nhour, minute, and second specified:" 98 << "n "; 99 t4.printMilitary(); 100 cout << "n "; 101 t4.printStandard(); 102 103 cout << "nall invalid values specified:" 104 << "n "; 105 t5.printMilitary(); 106 cout << "n "; 107 t5.printStandard(); 108 cout << endl; 109 110 return 0; 111 }
  • 11.
    Using Destructors • Destructors –Are member function of class – Perform termination housekeeping before the system reclaims the object’s memory – Name is tilde (~) followed by the class name (i.e., ~Time) – Receives no parameters, returns no value – One destructor per class (no overloading) – Destructors cannot be declared const, static – A destructor can be declared virtual or pure virtual
  • 12.
    When Constructors andDestructors Are Called Constructors and destructors called automatically – Order depends on scope of objects 1. Global scope objects – Constructors called before any other function (including main) – Destructors called when main terminates (or exit function called) – Destructors not called if program terminates with abort 2. Automatic local objects – Constructors called when objects are defined – Destructors called when objects leave scope – Destructors not called if the program ends with exit or abort
  • 13.
    7 class CreateAndDestroy{ 8 public: 9 CreateAndDestroy( int ); // constructor 10 ~CreateAndDestroy(); // destructor 11 private: 12 int data; 13 }; 14 15 #endif
  • 14.
    24 25 CreateAndDestroy::CreateAndDestroy( intvalue ) 26 { 27 data = value; 28 cout << "Object " << data << " constructor"; 29 } 30 31 CreateAndDestroy::~CreateAndDestroy() 32 { cout << "Object " << data << " destructor " << endl; } Constructor and Destructor changed to print when they are called.
  • 15.
    42 43 void create(void ); // prototype 44 45 CreateAndDestroy first( 1 ); // global object 46 47 int main() 48 { 49 cout << " (global created before main)" << endl; 50 51 CreateAndDestroy second( 2 ); // local object 52 cout << " (local automatic in main)" << endl; 53 54 static CreateAndDestroy third( 3 ); // local object 55 cout << " (local static in main)" << endl; 56 57 create(); // call function to create objects 58 59 CreateAndDestroy fourth( 4 ); // local object 60 cout << " (local automatic in main)" << endl; 61 return 0; 62 } 63 64 // Function to create objects 65 void create( void ) 66 { 67 CreateAndDestroy fifth( 5 ); 68 cout << " (local automatic in create)" << endl; 69 70 static CreateAndDestroy sixth( 6 ); 71 cout << " (local static in create)" << endl; 72 73 CreateAndDestroy seventh( 7 ); 74 cout << " (local automatic in create)" << endl; 75 }
  • 16.
    OUTPUT Object 1 constructor(global created before main) Object 2 constructor (local automatic in main) Object 3 constructor (local static in main) Object 5 constructor (local automatic in create) Object 6 constructor (local static in create) Object 7 constructor (local automatic in create) Object 7 destructor Object 5 destructor Object 4 constructor (local automatic in main) Object 4 destructor Object 2 destructor Object 6 destructor Object 3 destructor Object 1 destructor Notice how the order of the constructor and destructor call depends on the types of variables (automatic, global and static) they are associated with. Static objects are declared with the keyword static. They are initialized only once and stored in the static storage area. The static objects are only destroyed when the program terminates i.e. they live until program termination
  • 17.
    When do ConstructorsGet Called? • Class object creation time • Dynamically allocated object • Class argument passed by value • Class object returned by value • Object Array element (created)
  • 18.
    What Constructors Do •Help in initializing: class data members Employee( ) { id = 0; } • Allocate memory for dynamic members Employee() { char* nameptr = new char[20];} • Allocate any needed resources – Such as to open files, etc.
  • 19.
    Constructing Arrays ofObjects Complex c_arr[10]; Date date_arr[20]; Issue: There is no way to call argument-based constructors (non-default) for array members
  • 20.
    Arrays of Objectsand Non-Default Constructors • Trick: declare an array of pointer to objects • Allocate and initialize each object in a loop Date *dates[31]; for (int day = 0; day < 31; ++day) { dates[day] = new Date(3, day, 2020); }
  • 21.
    Default Member-wise Assignment •Assignment operator (=) can be used to assign an object to another object of the same type. • Member-wise assignment: each data member of the object on the right of the assignment operator is assigned individually to the same data member in the object on the left 

Editor's Notes

  • #3 #ifndef checks whether the given token has been #defined earlier in the file or in an included file; if not, it includes the code between it and the closing #else or, if no #else is present, #endif statement.
  • #5 When you define any an argument based constructor  YOU MUST ALO DEFINE A NO-ARGUMENT constructor yourself.
  • #8 A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values. When prototype is written then only prototype has default value but not the definition of function.
  • #11 const function: That cannot modify class data members static function: class level function (not assosiated with any object) virtual function: A C++ virtual function is a member function in the base class that you redefine in a derived class pure-virtual function: A pure virtual function is a virtual function in C++ for which we need not to write any function definition and only we have to declare it
  • #12 Abort: Aborts the current process, producing an abnormal program termination. exit() terminates the calling process without executing the rest code which is after the exit() function. The _Exit() function in C/C++ gives normal termination of a program without performing any cleanup tasks.
  • #17 Return by value calls copy constructor.