Download presentation
Presentation is loading. Please wait.
1
Topic 7 Introduction to Classes and Objects
2
Objectives (Chapter 8 in textbook)
You should be able to describe: Abstract Data Types in C++ (Classes) Constructors Problem Solving
3
Objects An object is simply a self-contained entity that has an existence independent of other entities a desk the chair that you are sitting on pens and pencils a book trains buildings paper cups
4
Classes and Objects A class can be expressed as a general form of an object, e.g.: The Golden Gate belongs to the class of bridges; The Sydney Opera House belongs to the class of buildings;
5
Abstract Data Types in C++ (Classes)
Object creation capability was provided by extending procedural language C Extensions became C++ Permits programmer to use and create objects Abstract data type: User-defined data type Central to creation of objects
6
Abstract Data Types Data type: Combination of data and associated operations Abstract data type: User-defined type Defines type of data and operations that can be performed on it Required to create objects more complex than simple integers and characters
7
Abstract Data Types (continued)
Once data type developed, programmers need never be concerned with how objects of data type stored or how operations are performed Need to know what operations do and how to invoke them Abstract data type referred to as a class
8
Class Construction Class defines both data and functions
Construct class in two parts: Declaration section Implementation section Class members: Variables and functions listed in class declaration section Data members: The variables Member functions: The functions
9
Attributes and Operations
Properties of the class Employee: Attributes (Data members) Operations (member functions) Name Hire Employee number Promote Job title Give pay rise Salary Fire Length of employment
10
Object type and Object instance
Object type (or class) is a generic description or definition of objects Object instance (or simply object) is a specific individual object of an object type. Every object is an instance of exactly one object type.
11
Object type and Object instance (ctd)
We will use the expression “define an object” to mean “define a new object type” or “define a new class” We will use the expression “declare an object” to mean “create a new object instance” An object type (class) must be defined before creating any object instance of that type
12
Object type and Object instance (ctd)
Think of the housing construction as an analogy: Defining an object (class) is equivalent to making the blueprint for a house. Just as having the blueprint does not imply the existence of an actual house, defining an object does not imply the existence of any actual object instance.
13
A C++ Class Declaration
class Name { public: // Public members go here private: // Private members go here };
14
Public and Private components
An object definition contains two basic components: private and public. Everything that is declared in the public section is accessible to the users of an object Everything that is declared in the private section is inaccessible to the users of an object. They can only be accessed by member functions. Default access for members of a class is private.
15
Public and Private components
The primary purpose of public members is to present to the class’s clients a view of the services (behaviors) the class provides. This set of services forms the public interface of the class. Clients of the class need not be concerned with how the class accomplishes its tasks. The private members of the class (as well as the definitions of public member functions) are not accessible to the clients of the class. These components form the implementation of the class.
16
The class Time class Time { public: Time();
void setTime(int, int, int); void print24hour(); void print12hour(); private: int hour; int minute; int second; };
17
More on private members
Private data does not necessarily mean that clients cannot change these data. Private data can be changed by member functions of that class. Access to these data is carefully controlled by the use of member functions. (e.g. member function setTime modifies the private data hour, minute, second)
18
More on private members
This modification seems to violate the notion of private data…. BUT a set function (such as setTime) can provide data validation capabilities (such as range checking) to ensure that the value is set properly. (It can also translate between the form of the data used in the interface and the form used in the implementation). Similarly for the print24hour function (it edits the data to be viewed by the client).
19
How to decide what is made public and what is made private
Keep all the data members of the class private. Provide public member functions to set and get the values of private data members. This architecture helps hide the implementation of a class from its clients, which reduces bugs and improves program modifiability. Not all member functions need be made public. Some member functions may remain private and serve as utility functions (also called helper functions) to other functions of the class.
20
Member functions of class Time
void Time::setTime(int h, int m, int s) { if ((h < 24) && (h >= 0)) hour = h; if ((m < 60) && (m >= 0)) minute = m; if ((s < 60) && (s >= 0)) second = s; }
21
Member functions of class Time (ctd)
void Time::print24hour() { cout<<hour<<":"<<minute<<":"<<second; } void Time::print12hour() if ((hour==0) || (hour==12)) cout<<12<<":"; else cout<<hour%12<<":"; cout<<minute<<":"<<second; if (hour<12) cout<<" AM"; cout <<" PM";
22
Creating and using objects
void main() { Time t; t.setTime(12,0,0); cout << "The time in 24 hour format is: "; t.print24hour(); cout << endl; cout << "The time in 12 hour format is: "; t.print12hour(); }
23
Constructors Any function with same name as its class
Initialize new object’s data members May also perform other tasks Multiple constructors can be defined for each class Function overloading Distinguishable by number and types of parameters No return type (not even void) is specified for a constructor
24
Constructors (ctd’) // Constructor simply initialises
// to zero the data members Time::Time() { hour = 0; minute = 0; second = 0; }
25
Constructors with parameters
// Constructor with parameters Time::Time(int h, int m, int s) { hour = h; minute = m; second = s; }
26
Creating an object with a parameterized constructor
// t is an object of class Time // and is initialised to midday Time t(12,0,0);
27
The complete program #include <iostream> using namespace std;
class Time { public: Time (); Time(int, int, int); void setTime(int, int, int); void print24hour(); void print12hour(); private: int hour; int minute; int second; }; Time::Time() //constructor without parameters { hour=0; minute=0; second=0; }
28
The complete program (ctd’)
Time::Time(int x, int y, int z) //constructor with parameters { hour=x; minute=y; second=z; } void Time::setTime(int h, int m, int s) if ((h<24) && (h>=0)) hour =h; if ((m<60) && (m>=0)) minute =m; if ((s<60) && (s>=0)) second =s;
29
The complete program (ctd’)
void Time::print24hour() { cout<<hour<<":"<<minute<<":"<<second; } void Time::print12hour() if ((hour==0) || (hour==12)) cout<<12<<":"; else cout<<hour%12<<":"; cout<<minute<<":"<<second; if (hour<12) cout<<" AM"; cout <<" PM";
30
The complete program (ctd’)
void main() { Time t1; //create an object instance - contructor //without parameters called Time t2(14,5,30); //create an obj. inst. - contructor //with parameters called t1.print12hour(); cout<<endl; t2.print24hour(); }
31
The fraction class #include <iostream> using namespace std;
class fraction{ public: fraction(); //constructor int numerator(); //returns the numerator of owner object int denominator(); //return the denominator void assign(int n, int d); //assigns values to num and denom fraction add(fraction f); //returns the sum of the owner object and f private: int num; int denom; };
32
The fraction class (ctd’)
fraction::fraction() { num=0; denom=1; } int fraction::numerator() return num; int fraction::denominator() return denom;
33
The fraction class (ctd’)
void fraction::assign(int n, int d) { num=n; denom=d; } fraction fraction::add(fraction f) fraction sum; sum.num=num*f.denom+f.num*denom; sum.denom=denom*f.denom; return sum;
34
The fraction class (ctd’)
void main() { fraction f, g, h, result; f.assign(1,3); //fraction f is assigned to 1 over 3 g.assign(1,4); //fraction g is assigned to 1 over 4 result=f.add(g); //adding f and g cout<<result.numerator()<<"/"<<result.denominator(); //gives 7/12 cout<<endl; }
35
Exercises Provide an additional, second constructor for the fraction object that initializes the numerator and denominator to some given values. Add the following functions to the fraction object: divide – returns the quotient of two fractions mult – returns the product dif – returns the difference
36
Exercise (ctd’) Write a private function reduce that reduces the fraction to its simplest form. E.g. 6/8 should be reduced to 3/4. (To reduce a fraction you divide both the numerator and the denominator by the greatest common divisor. You will need the gcd function we provided earlier in the course. This should also be a private function).
37
Arrays of Objects fraction farr[3];
Declares an array (called farr) of 3 fraction objects The constructor with no arguments is called automatically to initialize each element in the array To declare an initialize an array using a construction with arguments, we write: fraction farr[2]={fraction(2,3), fraction(1,4)};
38
Exercise Declare an array of 4 fraction objects, assign values to the data members of each one and perform the addition in pairs: first with second, third with fourth. Print the 4 fractions, along with the resulting additions.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.