0% found this document useful (0 votes)
119 views33 pages

Constructors and Destructors Presentation

This document discusses object-oriented programming and C++ classes. It introduces key concepts of OOP like encapsulation, information hiding, and classes as blueprints. It then demonstrates implementing a Time class with data members like hour, minute, second and member functions to set the time, and print it in military and standard time formats. The Time class constructor initializes the data members to default values. The document also discusses class scope and accessing members using the dot and arrow operators.

Uploaded by

Daniyal Hussain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
119 views33 pages

Constructors and Destructors Presentation

This document discusses object-oriented programming and C++ classes. It introduces key concepts of OOP like encapsulation, information hiding, and classes as blueprints. It then demonstrates implementing a Time class with data members like hour, minute, second and member functions to set the time, and print it in military and standard time formats. The Time class constructor initializes the data members to default values. The document also discusses class scope and accessing members using the dot and arrow operators.

Uploaded by

Daniyal Hussain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 33

Object Oriented

Programming
LECTURE 3
Introduction

 Object-oriented programming (OOP)


 Encapsulates data (attributes) and functions (behavior) into packages
called classes
 Data and functions closely related

 Information hiding
 Implementation details are hidden within the classes themselves

 Unit of C++ programming: the class


 A class is like a blueprint – reusable
 Objects are instantiated (created) from the class
 For example, a house is an instance of a “blueprint class”
 C programmers concentrate on functions
Implementing a Time Abstract Data Type
with a Class
 Classes
 Model objects that have attributes (data members) and behaviors (member
functions)
 Defined using keyword class

1 class Time {
2 public:
Public: and Private: are
3 Time(); member-access specifiers.
4 void setTime( int, int, int );
5 void printMilitary(); setTime, printMilitary, and
6 void printStandard(); printStandard are member
7 private: functions.
8 int hour; // 0 - 23
Time is the constructor.
9 int minute; // 0 - 59
10 int second; // 0 - 59
hour, minute, and
11 };
second are data
members.
Implementing a Time Abstract Data Type
with a Class (II)
 Format
 Body delineated with braces ({ and })
 Class definition terminates with a semicolon

 Member functions and data


Public - accessible wherever the program has access to an object of
class Time
Private - accessible only to member functions of the class
Protected - discussed later in the course
Implementing a Time Abstract Data Type
with a Class (III)
 Constructor
 Special member function that initializes data members of a class
object
 Constructors cannot return values
 Same name as the class
 Declarations
 Once class defined, can be used as a data type

Time sunset, // object of type Time


arrayOfTimes[ 5 ], // array of Time objects
*pointerToTime, // pointer to a Time object
&dinnerTime = sunset; // reference to a Time object

Note: The class


name becomes the
new type specifier.
Implementing a Time Abstract Data Type
with a Class (IV)
 Binary scope resolution operator (::)
 Specifies which class owns the member function
 Different classes can have the same name for member functions

 Format for definition class member functions


ReturnType ClassName::MemberFunctionName( ){

}
Implementing a Time Abstract Data Type
with a Class (V)
 If member function is defined inside the class
 Scope resolution operator and class name are not needed
 Defining a function outside a class does not change it being
public or private

 Classes encourage software reuse


 Inheritance allows new classes to be derived from old ones

 In following program
 Time constructor initializes the data members to 0
 Ensures that the object is in a consistent state when it is created
1 // Fig. 16.2: fig16_02.cpp
2 // Time class. Outline
3 #include <iostream>
4
5 using std::cout;
6 using std::endl; 1. Class definition
7
8 // Time abstract data type (ADT) definition
9 class Time {
1.1 Define default values
10 public:
11 Time(); // constructor
12 void setTime( int, int, int ); // set hour, minute, second
13 void printMilitary(); // print military time format
14 void printStandard(); // print standard time format
15 private:
16 int hour; // 0 – 23
17 int minute; // 0 – 59
18 int second; // 0 – 59
19 };
20
21 // Time constructor initializes each data member to zero.
22 // Ensures all Time objects start in a consistent state.
23 Time::Time() { hour = minute = second = 0; }
24
25 // Set a new Time value using military time. Perform validity
26 // checks on the data values. Set invalid values to zero.
27 void Time::setTime( int h, int m, int s )
28 {
29 hour = ( h >= 0 && h < 24 ) ? h : 0;
30 minute = ( m >= 0 && m < 60 ) ? m : 0;
31 second = ( s >= 0 && s < 60 ) ? s : 0;
32 }
33
34 // Print Time in military format Outline
35 void Time::printMilitary()
36 {
37 cout << ( hour < 10 ? "0" : "" ) << hour << ":"
38 << ( minute < 10 ? "0" : "" ) << minute; 1.2 Define the two
39 } functions
40 printMilitary and
41 // Print Time in standard format printstandard
42 void Time::printStandard()
43 { 2. In main(), create an
44 cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ) object of class Time.
45 << ":" << ( minute < 10 ? "0" : "" ) << minute
46 << ":" << ( second < 10 ? "0" : "" ) << second 2.1 Print the initial
47 << ( hour < 12 ? " AM" : " PM" ); (default) time
48 }
49
50 // Driver to test simple class Time
51 int main()
52 {
53 Time t; // instantiate object t of class Time
54
55 cout << "The initial military time is ";
56 t.printMilitary();
57 cout << "\nThe initial standard time is ";
58 t.printStandard();
59
60 t.setTime( 13, 27, 6 );
61 cout << "\n\nMilitary time after setTime is "; Outline
62 t.printMilitary();
63 cout << "\nStandard time after setTime is ";
64 t.printStandard();
65 2.2 Set and print the
66 t.setTime( 99, 99, 99 ); // attempt invalid settings time.
67 cout << "\n\nAfter attempting invalid settings:"
68 << "\nMilitary time: "; 2.3 Attempt to set the
69 t.printMilitary(); time to an invalid hour
70 cout << "\nStandard time: ";
71 t.printStandard(); 2.4 Print
72 cout << endl;
73 return 0;
74 }

The initial military time is 00:00


Program Output
The initial standard time is 12:00:00 AM
 
Military time after setTime is 13:27
Standard time after setTime is 1:27:06 PM
 
After attempting invalid settings:
Military time: 00:00
Standard time: 12:00:00 AM
Class Scope and Accessing Class Members

 Class scope
 Data members and member functions
 File scope
 Nonmember functions
 Function scope
 Variables defined in member functions, destroyed after function
completes
 Inside a scope
 Members accessible by all member functions
 Referenced by name
Class Scope and Accessing Class Members
(II)
 Outside a scope
 Use handles
 An object name, a reference to an object or a pointer to an object
 Accessing class members
 Same as structs
 Dot (.) for objects and arrow (->) for pointers
 Example: t.hour is the hour element of t
 TimePtr->hour is the hour element
1 // Fig. 16.3: fig16_03.cpp
2 // Demonstrating the class member access operators . and -> Outline
3 //
4 // CAUTION: IN FUTURE EXAMPLES WE AVOID PUBLIC DATA!
5 #include <iostream>
6 1. Class definition
7 using std::cout;
8 using std::endl; 1.1 Initialize object
9
10 // Simple class Count 2. Print using the dot
11 class Count { operator
12 public:
13 int x;
2.2 Set new value
14 void print() { cout << x << endl; }
15 };
2.3 Print using a
16
17 int main()
reference
18 {
19 Count counter, // create counter object
20 *counterPtr = &counter, // pointer to counter
21 &counterRef = counter; // reference to counter
22
23 cout << "Assign 7 to x and print using the object's name: ";
24 counter.x = 7; // assign 7 to data member x
25 counter.print(); // call member function print
26
27 cout << "Assign 8 to x and print using a reference: ";
28 counterRef.x = 8; // assign 8 to data member x
29 counterRef.print(); // call member function print
30
31 cout << "Assign 10 to x and print using a pointer: ";

32 counterPtr->x = 10; // assign 10 to data member x Outline


33 counterPtr->print(); // call member function print

34 return 0; 2.3 Set new value


35 }
2.4 Print using a pointer

Assign 7 to x and print using the object's name: 7


Assign 8 to x and print using a reference: 8 Program Output
Assign 10 to x and print using a pointer: 10
Controlling Access to Members

 Purpose of public
 Give clients a view of the services the class provides (interface)

 Purpose of private
 Default setting
 Hide details of how the class accomplishes its tasks (implementation)
 Private members only accessible through the public interface using
public member functions
1 // Fig. 16.5: fig16_05.cpp
2 // Demonstrate errors resulting from attempts Outline
3 // to access private class members.
4 #include <iostream>
5 1. Load header file for
6 using std::cout;
Time class.
7
8 #include "time1.h"
9 2. Create an object of
10 int main() class Time.
11 {
12 Time t; 2.1 Attempt to set a
13
14 // Error: 'Time::hour' is not accessible
private variable
15 t.hour = 7;
16 2.2 Attempt to access a
17 // Error: 'Time::minute' is not accessible private variable.
18 cout << "minute = " << t.minute;
19
20 return 0;
21 }

Compiling...
Fig06_06.cpp Program Output
D:\Fig06_06.cpp(15) : error C2248: 'hour' : cannot access private
member declared in class 'Time'
D:\Fig6_06\time1.h(18) : see declaration of 'hour'
D:\Fig06_06.cpp(18) : error C2248: 'minute' : cannot access private
member declared in class 'Time'
D:\time1.h(19) : see declaration of 'minute'
Error executing cl.exe.
 
test.exe - 2 error(s), 0 warning(s)
Access Functions and Utility Functions

 Utility functions
 private functions that support the operation of public functions
 Not intended to be used directly by clients
 Access functions
 public functions that read/display data or check conditions
 For a container, it could call the isEmpty function
 Next
 Program to take in monthly sales and output the total
 Implementation not shown, only access functions
87 // Fig. 16.6: fig16_06.cpp
88 // Demonstrating a utility function Outline
89 // Compile with salesp.cpp
90 #include "salesp.h"
91
92 int main() 1. Load header file
93 { (compile with file that
94 SalesPerson s; // create SalesPerson object s contains function
95 definitions)
96 s.getSalesFromUser(); // note simple sequential code
97 s.printAnnualSales(); // no control structures in main 1.1 Create an object
98 return 0;
99 } 2. Function calls

 OUTPUT
Enter sales amount for month 1: 5314.76 Program Output
Enter sales amount for month 2: 4292.38
Enter sales amount for month 3: 4589.83
Enter sales amount for month 4: 5534.03
Enter sales amount for month 5: 4376.34
Enter sales amount for month 6: 5698.45
Enter sales amount for month 7: 4439.22
Enter sales amount for month 8: 5893.57
Enter sales amount for month 9: 4909.67
Enter sales amount for month 10: 5123.45
Enter sales amount for month 11: 4024.97
Enter sales amount for month 12: 5923.92
 
The total annual sales are: $60120.59
Initializing Class Objects: Constructors

 Constructor function
 Can initialize class members
 Same name as the class, no return type
 Member variables can be initialized by the constructor or set afterwards

 Declaring objects
 Initializers can be provided
 Initializers passed as arguments to the class’ constructor
Constructors
A Member function with the same name as its classis
called Constructor and it is used to initilize the
objects of that class type with a legal value.
A Constructor is a special member function of a class
that is called automatically when an object of class
is created.
Example :
class Student
{
int rollno;
float marks;
public:
student( ) //Constructor
// Implicit Call
{ Student ob1;
rollno=0;
marks=0.0; // Explicit Call
} Student ob1=student();
//other public members
};
TYPES OF CONSRUCTORS

1. Default Constructor: A constructor that accepts no


parameter is called the Default Constructor. If you don't
declare a constructor or a destructor, the compiler makes
one for you. The default constructor and destructor take
no arguments and do nothing.

2. Parameterized Constructors: A constructor that accepts

parameters for its invocation is known as parameterized


Constructors ,also called as Regular Constructors
DESTRUCTORS

A destructor is also a member function whose


name is the same as the class name but is
preceded by tilde(“~”).It is automatically by the
compiler when an object is destroyed.

Destructors are usually used to deallocate


memory and do other cleanup for a class object
and its class members when the object is
destroyed.

A destructor is called for a class object when that


object passes out of scope or is explicitly deleted.
DESTRUCTORS

Example :
class TEST
{ int Regno,Max,Min,Score;
Public:
TEST( ) // Default Constructor
{}
TEST (int Pregno,int Pscore) // Parameterized Constructor
{
Regno = Pregno ;Max=100;Max=100;Min=40;Score=Pscore;
}
~ TEST ( ) // Destructor
{ Cout<<”TEST Over”<<endl;}
};
The following points apply to constructors and
destructors:

Constructors and destructors do not have return type, not


even void nor can they return values.

References and pointers cannot be used on constructors


and destructors because their addresses cannot be taken.

Constructors cannot be declared with the keyword virtual

Constructors and destructors cannot be declared static,


const, or volatile.

 Unions cannot contain class objects that have


constructors or destructors.
The following points apply to constructors and
destructors:

The compiler automatically calls constructors when defining


class objects and calls destructors when class objects go out
of scope

Derived classes do not inherit constructors or destructors


from their base classes, but they do call the constructor and
destructor of base classes.

The default destructor calls the destructors of the base


class and members of the derived class.
The following points apply to Constructors and
Destructors:

The destructors of base classes and members are called in


the reverse order of the completion of their constructor:

The destructor for a class object is called before destructors


for members and bases are called.
You can have only one destructor for a class.
Destructors can’t be overloaded.
They can not be inherited.
No argument can be provided to destructors.
Copy Constructor

A copy constructor is a special constructor in the C++


programming language used to create a new object as a
copy of an existing object.

A copy constructor is a constructor of the form classname


(classname &).The compiler will use the copy constructors
whenever you initialize an instance using values of another
instance of the same type.

Copying of objects is achieved by the use of a copy


constructor and a assignment operator.
Copy Constructor Example :
class Sample{ int i, j;
public:
Sample(int a, int b) // constructor
{ i=a;j=b;}
Sample (Sample & s) //copy constructor
{ j=s.j ; i=s.j;
cout <<”\n Copy constructor working \n”;
}
void print (void)
{cout <<i<< j<< ”\n”;}
};
Note : The argument to a copy constructor is passed by reference, the
reason being that when an argument is passed by value, a copy of it is
constructed. But the copy constructor is creating a copy of the object for
itself, thus ,it calls itself. Again the called copy constructor requires another
copy so again it is called. In fact it calls itself again and again until the
compiler runs out of the memory .so, in the copy constructor, the argument
must be passed by reference.
CALLING COPY CONSTRUCTOR

Sample s2(s1); // s1 is copied to s2. Copy constructor is called.

Sample s3=s1; // s1 is copied to s3. copy constructor called


again
When Copy Constructor is called?
When an object is passed by value to a function:
The pass by value method requires a copy of the passed
argument to be created for the function to operate upon .Thus
to create the copy of the passed object, copy constructor is
Invoked If a function with the following prototype :

void cpyfunc(Sample ); // Sample is a class then for the


following function call
cpyfunc(obj1); // obj1 is an object of Sample type the copy
constructor would be invoked to create a copy of the obj1
object for use by cpyfunc().
When Copy Constructor is called?
When a function returns an object :

When an object is returned by a function the copy constructor


is invoked
Sample cpyfunc(); // Sample is a class and it is return type
of cpyfunc()
If func cpyfunc() is called by the following statement
obj2 = cpyfunc();

Then the copy constructor would be invoked to create a copy


of the value returned by cpyfunc() and its value would be
assigned to obj2. The copy constructor creates a temporary
object to hold the return value of a function returning an
object.
Thank You
Very Much

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy