On completion of this chapter students will know how to: Define a class, use an object, select class data members, select class function members, create a constructor function, create overloaded constructor functions.
Trang 1Chapter 8 – Classes and Objects
Trang 2Classes form tightly knit group of functionsDistinct program boundaries
More reliable large programs
Reduces amount of programming done
“from scratch”
Lesson 8.1
Trang 3Data type created by grouping other data types
Contains data members
Defined by programmer – derived data typeDeclares space for all data members
Lesson 8.1
Trang 4Name of struct
Data members
Data type declaration for
each data member
Lesson 8.1
Trang 5Use struct name followed with names of variables
Example:
Fluid water, oil;
Lesson 8.1
Trang 7private_members; public:
public_members;};
Trang 8Listed as in ordinary declarations
– Type and identifier in sequence
Class definition does NOT reserve memory for class members
– Memory reserved when class declared
Cannot use storage class specifiers: auto, extern or register
Can be objects of other classes
Lesson 8.2
Trang 10Those not included inside class definition
– Require class name and scope resolution operator (::) to immediately precede function name
}
Trang 11– Declaration of objects of a particular class
(instances)
Lesson 8.2
Trang 13Class member function executed
automatically upon declaration of object
Frequently used to initialize values of data members
Can be called just Constructor
Lesson 8.3
Trang 15Lesson 8.3
class Name{
class name and constructor function name identical
Trang 16Lesson 8.3
Name : : Name ( ){
data_member = value;
}
Trang 18Constructor
Initialization list which follows single colon written after header
, …
Trang 19a Constructor Function
Cannot call like other member functions
Can call constructor a second time for that object using an assignment statement
Lesson 8.4
station1 = Weather_station (10);
Right side creates nameless object
that is assigned to station1
Trang 21Same name with different argument listsExample:
Lesson 8.5
Microwave_instruction ( ) ;Microwave_instruction (int);
Microwave_instruction (int, int);