You are on page 1of 36

CS/IS 135

PROGRAMMING IN C/C++
Class 11: Chapter 10 Introduction to Classes
November 18, 2017
Agenda

Object-Based Programming
Creating Your Own Classes
Constructors
Using Classes with Examples
Class Scope and Duration Categories
Break
Lab
Object-
Object-Based Programming

In contrast with Procedural programming


Object: well suited to programming representation
Can be specified by two basic characteristics:
State: how object appears at the moment
Behavior: how object reacts to external inputs
Example of an object: an elevator
State: size, location, interior decoration
Behavior: reaction when one of its buttons is pushed
A Class Is a Plan

Class can be considered a construction plan for objects and how they
can be used
Plan lists the required data items and supplies instructions for using the data
Many objects can be created from the same class
Each different object type requires its own class

Different cars can be created from a class Car

A skateboard CANNOT be created from a class Car.


It needs its class Skateboard
Class Components

Class has a name, a way to identify it.


Example: Elevator, Car

Class typically contains sections for :


Items (or data members)
int number_of_doors ;
string brand_name ;

Methods (or function)


double current_speed(int, int ) ;
Class Construction

Class: programmer-defined data type


Also called an abstract data type
Combination of data and their associated operations (capabilities)

Two components:
Declaration section: declares data types and function for class
Implementation section: defines functions whose prototypes were declared
in declaration section
Class Construction (cont'd.)

Notice the ;
It indicates the end of the class declaration
Class Construction (cont'd.)

Example of class declaration section:


class Date class name
{
private:
int month;
int day; data members
access specifiers int year;

public:
Date(int = 7, int = 4, int = 2012); member methods
void setDate(int, int, int);
void showDate(void);
}; // this is a declaration - don't forget the semicolon
Class Construction (cont'd.)

Declaration section of class definition


Enclosed in braces
Includes variables (data members) and function declarations
Keywords private and public: define access rights
private: class members (month, day, and year) can only be accessed using class
functions
Enforces data security (data hiding)

public: class members (functions Date(), setDate(), showDate()) can be used


outside of the class
Class Construction (cont'd.)

Constructor method: initializes class data members with values


Constructor function (Date()) has same name as the class
Default values for constructor are 7, 4, 2012
Constructor function has no return type (a requirement for this special
function)
Date(int = 7, int = 4, int = 2012);

Two remaining member functions: setDate() and showDate()


declared as returning no value (void)
void setDate(int, int, int);
void showDate(void);
Class Construction (cont'd.)
Implementation section of class definition

Except for constructor function, which has no return data type

Functions: defined the same as other C++ functions but also include
scope resolution operator :: to identify function as member of class
Class Construction (cont'd.)

Program10.1.cpp
Class Construction (cont'd.)
We defined the class. We can now create objects of this class

Creation of objects of Date class in main() function


int main()
{
Date a, b, c(4,1,2000); // declare 3 objects
b.setDate(12,25,2009); // assign values to b's data members
a.showDate(); // display object a's values
b.showDate(); // display object b's values
c.showDate(); // display object c's values
cout << endl;
return 0;
}
Class Construction (cont'd.)

Description of main():
Three objects of class Date defined
Constructor function: Date(), automatically called
Memory allocated for each object
Data members of the objects initialized
Object a: no parameters assigned; therefore, defaults are used:
a.month = 7
a.day = 4
a.year = 2012
Class Construction (cont'd.)

Description of main(): (cont'd.)


Notation to create objects:
objectName.attributeName
Object b: no parameters assigned, same defaults used
Object c: defined with arguments 4, 1, and 1998
Three arguments passed into constructor function resulting in initialization of cs data
members as:
c.month = 4
c.day = 1
c.year = 2000
Class Construction (cont'd.)

Description of main(): (cont'd.)


All functions of class Date are public; therefore:
b.setDate(12, 25, 2009) is a valid statement inside main() function
Calls setDate() function with arguments 12 ,25, 2009

Important distinction: data members of class Date are private


The statement b.month = 12 is invalid in main()
Class Construction (cont'd.)

Description of main(): (cont'd.)


Last three statements in main() call showDate() to operate on a, b, and
c objects
Calls result in output displayed by Program 10.1
The date is 07/04/12
The date is 12/25/09
The date is 04/01/00

The statement cout << a; is invalid within main()


cout does not know how to handle an object of class Date
Terminology

Class: programmer-defined data type


Objects (instances): created from classes
Relation of objects to classes is similar to relation of variables to C++ built-in
data types
int a; // a is a variable of type integer
Date a; // a is an object of class Date
Instantiation: process of creating a new object
Creates new set of data members belonging to new object: determines the objects state
Terminology (cont'd.)

Interface: part of class declaration section


Includes:
Classs public member function declarations
Supporting comments
Implementation consists of:
Implementation section of class definition
Private member functions
Public member functions
Private data members from class declaration section
Agenda

Object-Based Programming
Creating Your Own Classes
Constructors
Using Classes with Examples
Class Scope and Duration Categories
Break
Lab
Constructors

A function that has the same name as its class


Must have no return type
Multiple constructors can be defined for a class
Each must be distinguishable by the number and types of its parameters

If no constructor function is written, compiler assigns default constructor


Purpose: Initialize a new objects data members
May perform other tasks
Constructors (cont'd.)

Default constructor: does not require arguments when called


Two cases:
No parameters declared
As with compiler-supplied default constructor
Arguments have already been given default values in valid prototype statement:
Date (int = 7, int = 4, int = 2012)
Declaration Date a; initializes the a object with default values: 7, 4, 2012
Constructors (cont'd.)
Sample class declaration:
class Date
{
private:
int month, day, year;
public:
void setDate(int, int, int);
void showDate()
};

No constructor has been included


Compiler assigns a do-nothing default constructor equivalent to:
Date () { }
This constructor expects no parameters and has an empty body
Constructors (cont'd.)
Use of constructor in main() : Program 10.2
int main()
{
Date a; // declare an object
Date b; // declare an object
Date c (4,1,2009); // declare an object
return 0;
}

Output:
Created a new data object with data values 7, 4, 2012
Created a new data object with data values 7, 4, 2012
Created a new data object with data values 4, 1, 2009
Calling Constructors

Constructors are called whenever an object is created


Date c(4,1,2009);
Date c = Date(4,1,2009);
Object should never be declared with empty parentheses
Constructors are called automatically each time an object is created
Other methods must be called explicitly by name
Constructors can:
Have default arguments (as in Program 10.1)
Be overloaded
Be written as inline functions
Destructors

Counterpart of constructor function


Has same name as constructor
Preceded with a tilde (~)
Date class constructor: ~Date()
Default destructor
Do-nothing destructor provided by C++ compiler in absence of explicit
destructor
Can only be one destructor per class
Destructors take no values and return no arguments

Program 10.4
Arrays of Objects

Declaring array of objects is the same as declaring array of C++ built-


in type
Example: Date theDate[5];
Creates five objects named theDate[0] through theDate[4]
Member functions for theDate array objects are called using:
objectName.functionName
Agenda

Object-Based Programming
Creating Your Own Classes
Constructors
Using Classes with Examples
Class Scope and Duration Categories
Break
Lab
Example 1: Constructing a Room Object

We want to create a class representing a Room. This class will be able


to:
Display the room length and width
Modify the value of the room length and width
Determine the floor area of a rectangular room
Example 1: Constructing a Room Object

Solution: Program 10.5


One type of object: rectangular-shaped room
Represented by two double precision variables: length and width

Functions needed:
Constructor: to specify an actual length and width value when a room is
instantiated
Accessor: to display rooms length and width
Mutator: to change above values
Function to calculate rooms floor area from its length and width values
Example 2: Constructing an Elevator Object

Simulate an elevators operation


Solution: Program 10.6

One type of object: elevator


Three attributes: elevators number, current location, and highest floor it can reach

Functions needed:
Constructor: initializes the elevators number, starting floor position, and highest floor
request(): to alter the elevators position
Class Scope and Duration Categories

Scope of an identifier: defines the portion of a program where the


identifier is valid

Class data members are local to the class in which theyre declared

Class method names are local to the class theyre declared in and
can be used only by objects declared for the class
Class Scope and Duration Categories (contd.)
Static Class Members

As each class object is created, it gets its own block of memory for its
data members
In some cases, its convenient for every created object to share the
same memory location for a specific variable
C++ handles this situation by declaring a class variable to be static

Static class variables share the same storage space for all class objects
They act as global variables for the class and provide a means of
communication between objects

Program 10.7
Friend Functions

Friend functions
Nonmember methods that are granted the same privileges as its member
methods
Series of method prototype declarations preceded with the keyword friend
and included in the class declaration section

Program 10.9
Break !

Lab 6 next
Homework 6 is posted

Both due at (Before) Final exam date December 9

Next Week : Thanksgiving break

You might also like