0% found this document useful (0 votes)
51 views

Lecture 10 - Classes 1

This document discusses classes in object-oriented programming using C++. It introduces key concepts like encapsulation, information hiding, and classes as blueprints for objects. An example Time class is implemented to demonstrate defining classes with data members and member functions, and using the class to instantiate Time objects. Member functions are defined both inside and outside the class, and the scope resolution operator :: is used when defining functions outside the class. The document also covers accessing class members using the dot . and arrow -> operators.

Uploaded by

Shaheer Alam
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

Lecture 10 - Classes 1

This document discusses classes in object-oriented programming using C++. It introduces key concepts like encapsulation, information hiding, and classes as blueprints for objects. An example Time class is implemented to demonstrate defining classes with data members and member functions, and using the class to instantiate Time objects. Member functions are defined both inside and outside the class, and the scope resolution operator :: is used when defining functions outside the class. The document also covers accessing class members using the dot . and arrow -> operators.

Uploaded by

Shaheer Alam
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 23

Lecture 10: Classes-I CS 112: Programming Techniques

Classes-I

Dr. Zahid Halim

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


Lecture 10: Classes-I CS 112: Programming Techniques

Introduction
• Object-oriented programming (OOP)
– Encapsulates data (attributes) and functions (behavior) into packages
called classes
• Information hiding
– Implementation details are hidden within the classes themselves
• Classes
– Classes are the standard unit of programming
– 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”

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


Lecture 10: Classes-I CS 112: Programming Techniques
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
– Have a body delineated with braces ({ and })
– Class definitions terminate with a semicolon
– Example:
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 second are
11 };
data members.
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 10: Classes-I CS 112: Programming Techniques
Implementing a Time Abstract Data Type with a
• Member access specifiers
Class
– Classes can limit the access to their member functions and data
– The three types of access a class can grant are:
• Public — Accessible wherever the program has access to
an object of the class
• private — Accessible only to member functions of the class
• Protected — Similar to private and discussed later
• Constructor
– Special member function that initializes the data members of a class
object
– Cannot return values
– Have the same name as the class

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


Lecture 10: Classes-I CS 112: Programming Techniques
Implementing a Time Abstract Data Type with a
Class
• Class definition and declaration
– Once a class has been defined, it can be used as a type in object, array
and pointer declarations
– Example:
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.

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


1 // Fig. 6.3: fig06_03.cpp
2 // Time class.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 // Time abstract data type (ADT) definition
9 class Time {
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. Note the :: preceding
23 Time::Time() { hour = minute = second = 0; }
the function names.
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
35 void Time::printMilitary()
36 {
37 cout << ( hour < 10 ? "0" : "" ) << hour << ":"
38 << ( minute < 10 ? "0" : "" ) << minute;
39 }
40
41 // Print Time in standard format
42 void Time::printStandard()
43 {
44 cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 )
45 << ":" << ( minute < 10 ? "0" : "" ) << minute
46 << ":" << ( second < 10 ? "0" : "" ) << second
47 << ( hour < 12 ? " AM" : " PM" );
48 }
49
50 // Driver to test simple class Time
51 int main()
52 {
53 Time t; // instantiate object t of class The
Timeinitial military time is 00:00
The initial standard time is 12:00:00 AM
54
55 cout << "The initial military time is ";
56 t.printMilitary(); Notice how functions
57 cout << "\nThe initial standard time is "; are called using the dot
58 t.printStandard(); (.) operator.
59
60 t.setTime( 13, 27, 6 );
61 cout << "\n\nMilitary time after setTime is ";
62 t.printMilitary();
63 cout << "\nStandard time after setTime is ";
64 t.printStandard();
Military time after setTime is 13:27
65 Standard time after setTime is 1:27:06 PM
66 t.setTime( 99, 99, 99 ); // attempt invalid settings
67 cout << "\n\nAfter attempting invalid settings:"
68 << "\nMilitary time: ";
69 t.printMilitary();
70 cout << "\nStandard time: ";
71 t.printStandard(); After attempting invalid settings:
72 cout << endl; Military time: 00:00
73 return 0; Standard time: 12:00:00 AM
74 }

The initial military time is 00:00


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
Lecture 10: Classes-I CS 112: Programming Techniques
Implementing a Time Abstract Data Type with a
Class
• Destructors
– Functions with the same name as the class but preceded with a tilde
character (~)
– Cannot take arguments and cannot be overloaded
– Performs “termination housekeeping”
• Binary scope resolution operator (::)
– Combines the class name with the member function name
– Different classes can have member functions with the same name
• Format for defining member functions
ReturnType ClassName::MemberFunctionName( ){

}

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


Lecture 10: Classes-I CS 112: Programming Techniques
Implementing a Time Abstract Data Type with a
Class
• If a 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

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


Lecture 10: Classes-I CS 112: Programming Techniques

Class Scope and Accessing Class Members


• Class scope
– Data members and member functions
• File scope
– Nonmember functions
• Inside a scope
– Members accessible by all member functions
• Referenced by name
• Outside a scope
– Members are referenced through handles
• An object name, a reference to an object or a pointer to
an object

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


Lecture 10: Classes-I CS 112: Programming Techniques

Class Scope and Accessing Class Members


• Function scope
– Variables only known to function they are defined in
– Variables are destroyed after function completion
• 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

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


1 // Fig. 6.4: fig06_04.cpp
2 // Demonstrating the class member access operators . and ->
3 //
4 // CAUTION: IN FUTURE EXAMPLES WE AVOID PUBLIC DATA!
5 #include <iostream> It is rare to have
6 public member
variables. Usually only
7 using std::cout;
member functions are
8 using std::endl; public; this keeps as
9 much information
10 // Simple class Count hidden as possible.
1. Class definition
11 class Count {
12 public:
2. Create an object of the class
13 int x;
14 2.1 Assign
void a value
print() to the object.
{ cout << x << Printendl;
the value
} using the dot operator
15 };
2.2 Set a new value and print it using a reference
16
17 int main()
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

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

34 return 0;

35 }

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


Assign 8 to x and print using a reference: 8
Assign 10 to x and print using a pointer: 10
Lecture 10: Classes-I CS 112: Programming Techniques

Separating Interface from 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

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


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 Dot ( . ) replaced with underscore ( _ ) in file name.

7 #define TIME1_H
8
If time1.h (TIME1_H) is not defined (#ifndef)
9 // Time abstract data type definition then it is loaded (#define TIME1_H). If TIME1_H
is already defined, then everything up to #endif is
10 class Time {
ignored.
11 public: This prevents loading a header file multiple times.

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
23 // Fig. 6.5: time1.cpp
24 // Member function definitions for Time class.
25 #include <iostream>
26
27 using std::cout;
28 Source file uses #include to load
29 #include "time1.h" the header file
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; Source file contains function
42 } definitions
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 }
Lecture 10: Classes-I CS 112: Programming Techniques

Controlling Access to Members


• public
– Presents clients with a view of the services the class provides (interface)
– Data and member functions are accessible
• private
– Default access mode
– Data only accessible to member functions and friends
– private members only accessible through the public class interface
using public member functions

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


1 // Fig. 6.6: fig06_06.cpp
2 // Demonstrate errors resulting from attempts
3 // to access private class members.
4 #include <iostream>
5
6 using std::cout;
7
8 #include "time1.h"
9
10 int main()
11 {
12 Time t;
13
14 // Error: 'Time::hour' is not accessible
15 t.hour = 7; Attempt to modify private member variable
hour.
16
17 // Error: 'Time::minute' is not accessible
18 cout << "minute = " << t.minute;
19 Attempt to access private member variable
minute.
20 return 0;
21 }

Compiling...
Fig06_06.cpp
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)


Lecture 10: Classes-I CS 112: Programming Techniques

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
– Allow public functions to check private data

• Following example
– Program to take in monthly sales and output the total
– Implementation not shown, only access functions

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


87 // Fig. 6.7: fig06_07.cpp
88 // Demonstrating a utility function
89 // Compile with salesp.cpp
90 #include "salesp.h" Create object s, an instance of
91 class SalesPerson
92 int main()
93 {
94 SalesPerson s; // create SalesPerson object s
95
96 s.getSalesFromUser(); // note simple sequential code
97 s.printAnnualSales(); // no control structures in main
98 return 0;
99 }
Use access functions to gather and
print data (getSalesFromUser and
OUTPUT printAnnualSales). Utility functions
Enter sales amount for month 1: 5314.76 actually calculate the total sales, but the
Enter sales amount for month 2: 4292.38 user is not aware of these function calls.
Enter sales amount for month 3: 4589.83 Notice how simple main() is – there
Enter sales amount for month 4: 5534.03 are no control structures, only function
Enter sales amount for month 5: 4376.34 calls. This hides the implementation of
Enter sales amount for month 6: 5698.45 the program.
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


Lecture 10: Classes-I Quiz-1 CS 112: Programming Techniques

• In this quiz you have to write a solution for course record system
of GIK. The university mentions a list of students consisting of
their Roll No., Name, Age, Current Semester, CGPA, Faculty,
Date of Birth, Address, Cell No and Courses (it will be a list of
5 courses). Each course will have its Title, Credit hours and
Course Code.

• Write a program that uses structures to represent both student


and course. Note course will be a member of student structure
as an array of size 5.

• Your program should declare only one instance of structure


Student and initialize its members.

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


Lecture 10: Classes-I CS 112: Programming Techniques

References
• Book Code: A

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi

You might also like