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

CP Week 05 06 Structures and Classes

Uploaded by

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

CP Week 05 06 Structures and Classes

Uploaded by

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

Classes and Data Abstraction

Outline
Introduction
Structure Definitions
Accessing Members of Structures
Implementing a User-Defined Type Time with a Struct
Implementing a Time Abstract Data Type with a Class
Class Scope and Accessing Class Members
Controlling Access to Members
Separating Interface from Implementation
Initializing Class Objects: Constructors
Using Default Arguments with Constructors
Using Destructors
When Constructors and Destructors Are Called
Using Data Members and Member Functions
Assignment by Default Memberwise Copy
Software Reusability

Computer Programming 1
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 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”
Computer Programming 2
Structure Definitions (I)
• Structures
– aggregate data types built using elements of other types
including other structs

struct Time {
int hour; Structure tag
int minute;
Structure members
int second;
};

• Members of the same structure must have unique names


• Two different structures may contain members of the same name
• Each structure definition must end with a semicolon.

Computer Programming 3
Structure Definitions (II)
• self-referential structure
– Contains a member that is a pointer to the same structure
type
– Used for linked lists, queues, stacks and trees
• Struct
– creates a new data type that is used to declare variables.
– Structure variables are declared like variables of other
types
– For example:
Time timeObject, timeArray[ 10 ], *timePtr,
&timeRef = timeObject;
Computer Programming 4
Accessing Members of Structures

• member access operators:


– dot operator (.) for structures and objects
– arrow operator (->) for pointers

• Print member hour of timeObject:


cout << timeObject.hour;
OR
timePtr = &timeObject; // timePtr ptr to timeObject
cout << timePtr->hour; // prints timeObject.hour

• timePtr->hour same as (*timePtr).hour

Computer Programming 5
Create a structure, set its members, and print it.
#include <iostream>
using namespace std;

struct Time
{ // structure definition
int hour; // 0-23
int minute; // 0-59
int second; // 0-59
};

void printMilitary( const Time & ); // prototype


void printStandard( const Time & ); // prototype

int main()
{
Time dinnerTime; // variable of new type Time

// set members to valid values


dinnerTime.hour = 18;
Computer Programming 6
dinnerTime.minute = 30;
dinnerTime.second = 0;

cout << "Dinner will be held at ";


printMilitary( dinnerTime );

cout << " military time,\nwhich is ";


printStandard( dinnerTime );
cout << " standard time.\n";

// set members to invalid values


dinnerTime.hour = 29;
dinnerTime.minute = 73;

cout << "\nTime with invalid values: ";


printMilitary( dinnerTime );

return 0;
}

Computer Programming 7
// Print the time in military format
void printMilitary( const Time &t )
{
cout << ( t.hour < 10 ? "0" : "" ) << t.hour << ":“
<< ( t.minute < 10 ? "0" : "" ) << t.minute;
}

// Print the time in standard format


void printStandard( const Time &t )
{
cout << ( ( t.hour == 0 || t.hour == 12 ) ? 12 : t.hour % 12 )
<< ":" << ( t.minute < 10 ? "0" : "" ) << t.minute
<< ":" << ( t.second < 10 ? "0" : "" ) << t.second
<< ( t.hour < 12 ? " AM" : " PM" );
}

Computer Programming 8
Program Output

Dinner will be held at 18:30 military time,


which is 6:30:00 PM standard time.

Time with invalid values: 29:73


Implementing a Time Abstract Data Type with a
Class (I)
• Model objects that have attributes (data members) and
behaviors (member functions).
• defined using keyword class
• The body delineated with braces ({ and }).
• Class definition terminates with a semicolon.

• Member functions and data can be:
Public - accessible wherever the program has access to
an object of class Time.
• Private - accessible only to member functions of the
class.
• Protected – Accessible by sub-classes only
Computer Programming 10
Structure vs Class example
struct Time
{ // structure definition
int hour; // 0-23
int minute; // 0-59
int second; // 0-59
};

class Time
Public: and Private: are
{
member-access specifiers.
public:
Time(); setTime, printMilitary, and
void setTime( int, int, int ); printStandard are member
void printMilitary(); functions.
void printStandard(); Time is the constructor.

hour, minute, and


private: second are data members.
int hour; // 0 – 23
int minute; // 0 – 59
int second; // 0 – 59
};
Computer Programming 11
Implementing a Time Abstract Data Type with a
Class (II)
• constructor - special member function that initializes the
data members of a class object.
– Constructors cannot return values.
– same name as the class
• Once the class has been defined, it can be used as a type
in object, array and pointer definitions as follows:

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.
Computer Programming 12
// Time class Program
#include <iostream>
using namespace std;

// Time abstract data type (ADT) definition


class Time {
public:
Time(); // constructor
void setTime( int, int, int ); // set hour, minute, second
void printMilitary(); // print military time format
void printStandard(); // print standard time format
private:
int hour; // 0 – 23
int minute; // 0 – 59
int second; // 0 – 59
};
// Time constructor initializes each data member to zero.
// Ensures all Time objects start in a consistent state.
Time::Time() { hour = minute = second = 0; }

Computer Programming 13
// Set a new Time value using military time. Perform validity
// Ensures all Time objects start in a consistent state.
void Time::setTime( int h, int m, int s )
{
hour = ( h >= 0 && h < 24 ) ? h : 0;
minute = ( m >= 0 && m < 60 ) ? m : 0;
second = ( s >= 0 && s < 60 ) ? s : 0;
}

// Print Time in military format


void Time::printMilitary()
{
cout << ( hour < 10 ? "0" : "" ) << hour << ":"
<< ( minute < 10 ? "0" : "" ) << minute;
}
// Print Time in standard format
void Time::printStandard()
{
cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 )
<< ":" << ( minute < 10 ? "0" : "" ) << minute
<< ":" << ( second < 10 ? "0" : "" ) << second
<< ( hour < 12 ? " AM" : " PM" );
}
Computer Programming 14
// Driver to test simple class Time
int main()
{
Time t; // instantiate object t of class Time

cout << "The initial military time is ";


t.printMilitary();

cout << "\nThe initial standard time is ";


t.printStandard();

t.setTime( 13, 27, 6 );

cout << "\n\nMilitary time after setTime is ";


t.printMilitary();

cout << "\nStandard time after setTime is ";


t.printStandard();

t.setTime( 99, 99, 99 ); // attempt invalid settings


cout << "\n\nAfter attempting invalid settings:“
<< "\nMilitary time: ";

Computer Programming 15
t.printMilitary();

cout << "\nStandard time: ";


t.printStandard();

return 0;
}

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

Computer Programming 16
Implementing a Time Abstract Data Type with a
Class (III)
• A class’ private data members are normally not
accessible outside the class.

• The 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( )
{

}
Computer Programming 17
Implementing a Time Abstract Data Type with a
Class (IV)

• 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
• In this program, the Time constructor simply
initializes the data members to 0
– This ensures that the object is in a consistent state when it is
created.
• Classes encourage software reuse
– Inheritance allows new classes to be derived from old ones.

Computer Programming 18
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 - use handles
– an object name, a reference to an object or a pointer to an object.
• Function scope
– variables defined in member functions, destroyed after function completes.
• 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.
Computer Programming 19
Controlling Access to Members

• Purpose of public
– present 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.

Computer Programming 20
// Demonstrate errors resulting from attempts to
access private class members.
#include <iostream>
using namespace std;

// Time abstract data type (ADT) definition


class Time {
public:
Time(); // constructor
void setTime( int, int, int ); // set hour, minute, second
void printMilitary(); // print military time format
void printStandard(); // print standard time format
private:
int hour; // 0 – 23
int minute; // 0 – 59
int second; // 0 – 59
};
// Time constructor initializes each data member to zero.
// Ensures all Time objects start in a consistent state.
Time::Time() { hour = minute = second = 0; }

Computer Programming 21
// Driver to test simple class Time
int main()
{
Time t; // instantiate object t of class Time

// Error: 'Time::hour' is not accessible


t.hour = 7;

// Error: 'Time::minute' is not accessible


cout << "minute = " << t.minute;

return 0;
}

Compiling...

error C2248: 'hour' : cannot access private


member declared in class 'Time'
see declaration of 'hour'
error C2248: 'minute' : cannot access private
member declared in class 'Time'

test.exe - 2 error(s), 0 warning(s)


Computer Programming 22
Demonstrating the class member access
operators . and ->
#include <iostream>
using namespace std;

// Simple class Count


class Count {
public:
int x;
void print() { cout << x << endl; }
};

int main()
{
Count counter, // create counter object
*counterPtr = &counter, // pointer to counter
&counterRef = counter; // reference to counter

cout << "Assign 7 to x and print using the object's name: ";
counter.x = 7; // assign 7 to data member x
counter.print(); // call member function print

Computer Programming 23
cout << "Assign 8 to x and print using a reference: ";
counterRef.x = 8; // assign 8 to data member x
counterRef.print(); // call member function print

cout << "Assign 10 to x and print using a pointer: ";


counterPtr->x = 10; // assign 10 to data member x
counterPtr->print(); // call member function print

return 0;
}
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

A pointer in C++ is a variable that holds the memory address of


another variable.
A reference is an alias for an already existing variable. Once a reference
is initialized to a variable, it cannot be changed to refer to another
variable.
Computer Programming 24
Separating Interface from Implementation
• Separating interface from implementation makes it easier
to modify programs.
• C++ programs can be split into:
Header files – contains class definitions and function
prototypes
Source-code files – contains member function
definitions.
• Psuedocode Outline:
1. Using the same Time class as before, create a header file.
2. Create a source code file.
2.1 Load the header file to get the class definitions.
2.2. Define the member functions of the class.
Computer Programming 25
time1.h
// Declaration of the Time class.
// Member functions are defined in time1.cpp

// prevent multiple inclusions of header file


#ifndef TIME1_H
#define TIME1_H If time1.h (TIME1_H) is not
// Time abstract data type definition defined (#ifndef) then it is loaded
(#define TIME1_H). If
class Time {
TIME1_H is already defined, then
public: everything up to #endif is
Time(); // constructor ignored.
void setTime( int, int, int ); // set hour,
This minute,
prevents second
loading a header file
void printMilitary(); // print military time
multiple times.format
void printStandard(); // print standard time format
private:
int hour; // 0 – 23
int minute; // 0 – 59
int second; // 0 – 59
};
#endif
Computer Programming 26
time1.cpp
// Member function definitions for Time class.
#include <iostream>
using namespace std; Source file uses #include
#include "time1.h" to load the header file
// Set a new Time value using military time. Perform validity
void Time::setTime( int h, int m, int s ) {
hour = ( h >= 0 && h < 24 ) ? h : 0;
minute = ( m >= 0 && m < 60 ) ? m : 0;
second = ( s >= 0 && s < 60 ) ? s : 0;
}
// Print Time in military format
void Time::printMilitary() { Source file contains
cout << ( hour < 10 ? "0" : "" ) << hour << ":"function definitions
<< ( minute < 10 ? "0" : "" ) << minute;
}
// Print Time in standard format
void Time::printStandard(){
cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 )
<< ":" << ( minute < 10 ? "0" : "" ) << minute
<< ":" << ( second < 10 ? "0" : "" ) << second
<< ( hour < 12 ? " AM" : " PM" );
}
Computer Programming 27
Main_Program1.cpp
// Driver to test simple class Time
#include <iostream>
using namespace std;
#include "time1.h"
int main()
{
Time t; // instantiate object t of class Time

cout << "The initial military time is ";


t.printMilitary();
cout << "\nThe initial standard time is ";
t.printStandard();

t.setTime( 13, 27, 6 );

cout << "\n\nMilitary time after setTime is ";


t.printMilitary();
cout << "\nStandard time after setTime is ";
t.printStandard();

return 0;
}
Computer Programming 28
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.

• When an object of a class is declared, initializers can be


provided.
– These initializers are passed as arguments to the class’
constructor.
• Format:
Type ObjectName(value1,value2,…);

Computer Programming 29
Default Constructors

• constructor assigns value1, value2, etc. to its


member variables.
– If not enough values specified, rightmost parameters set to
default

• Default arguments
– set in constructor function prototype (in the class definition)

Computer Programming 30
time2.h
// Declaration of the Time class.
// Member functions are defined in time2.cpp

// prevent multiple inclusions of header file


#ifndef TIME1_H
#define TIME1_H
// Time abstract data type definition
class Time {
public:
Time( int = 0, int = 0, int = 0 ); // default constructor
void printMilitary(); // print military time format
void printStandard(); // print standard time format
private:
int hour; // 0 – 23
int minute; // 0 – 59
int second; // 0 – 59
};
#endif

Computer Programming 31
time2.cpp
// Member function definitions for Time class.
#include <iostream>
using namespace std;
#include "time2.h"
// Default Time constructor initializes each data member
Time::Time(int h, int m, int s) {
hour = ( h >= 0 && h < 24 ) ? h : 0;
minute = ( m >= 0 && m < 60 ) ? m : 0;
second = ( s >= 0 && s < 60 ) ? s : 0;
}
// Print Time in military format
void Time::printMilitary() {
cout << ( hour < 10 ? "0" : "" ) << hour << ":"
<< ( minute < 10 ? "0" : "" ) << minute;
}
// Print Time in standard format
void Time::printStandard(){
cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 )
<< ":" << ( minute < 10 ? "0" : "" ) << minute
<< ":" << ( second < 10 ? "0" : "" ) << second
<< ( hour < 12 ? " AM" : " PM" ) << endl << endl;
}
Computer Programming 32
Main_Program2.cpp
// Driver to test simple class Time
#include <iostream>
using namespace std;
#include "time2.h"
int main()
{
Time t1, // all arguments defaulted
t2(2), // minute and second defaulted
t3(21, 34), // second defaulted
t4(12, 25, 42), // all values specified
t5(27, 74, 99); // all bad values specified

cout << “Object t1: \n Millitary Time = ";


t1.printMilitary();
cout << "\nStandard Time = ";
t1.printStandard();

cout << “Object t2: \n Millitary Time = ";


t2.printMilitary();
cout << "\nStandard Time = ";
t2.printStandard();

Computer Programming 33
Main_Program2.cpp
cout << “Object t3: \n Millitary Time = ";
t3.printMilitary();
cout << "\nStandard Time = ";
t3.printStandard();

cout << “Object t4: \n Millitary Time = ";


t4.printMilitary();
cout << "\nStandard Time = ";
t4.printStandard();

cout << “Object t5: \n Millitary Time = ";


t5.printMilitary();
cout << "\nStandard Time = ";
t5.printStandard();

return 0;

Computer Programming 34
OUTPUT
Object t1:
Millitary Time = 00:00
Standard Time = 12:00:00 AM

Object t2:
Millitary Time = 02:00
Standard Time = 2:00:00 AM

Object t3:
Millitary Time = 21:34
Standard Time = 9:34:00 PM

Object t4:
Millitary Time = 12:25
Standard Time = 12:25:42 PM

Object t5:
Millitary Time = 00:00
Standard Time = 12:00:00 AM
Using Destructors
• Destructor –member function of class
– performs termination housekeeping before the
system reclaims the object’s memory.
– complement of the constructor
– name is tilde (~) followed by the class name. i.e.,
~Time.
• Recall that the constructor’s name is the class name.
– receives no parameters, returns no value.
– one destructor per class - no overloading allowed

Computer Programming 36
When Constructors and Destructors Are Called

• Constructors and destructors called automatically.


– order depends on scope of objects

• Global scope objects


– Constructors called before any other function (including main)
– Destructors called when main terminates (or exit function
called)
– Destructors not called if program terminates with abort

Computer Programming 37
When Constructors and Destructors Are Called (II)

• automatic local objects


– Constructors called when objects defined
– Destructors called when objects leave scope (when the block
in which they are defined is exited)
– Destructors not called if program ends with exit or abort

• static local objects


– Constructors called when execution reaches the point where
the objects are defined.
– Destructors called when main terminates or the exit
function is called
– Destructors not called if the program ends with abort

Computer Programming 38
create.h
// Definition of class CreateAndDestroy.

// Member functions defined in create.cpp

// prevent multiple inclusions of header file


#ifndef CREATE_H
#define CREATE_H
// Create abstract data type definition
class CreateAndDestroy {
public:
CreateAndDestroy( int ); // constructor
~CreateAndDestroy(); // destructor
private:
int data;

};
#endif

Computer Programming 39
create.cpp
// Member function definitions for class CreateAndDestroy
#include <iostream>
using namespace std;
#include "create.h"
// Create constructor
CreateAndDestroy::CreateAndDestroy( int value )
{
data = value;
cout << "Object " << data << " constructor";
}

// Create destructor
CreateAndDestroy::~CreateAndDestroy()
{

cout << "Object " << data << " destructor " << endl;

Computer Programming 40
Main_Program3.cpp
// Demonstrating the order in which constructors and
// destructors are called.

#include <iostream>
using namespace std;
#include "create.h“

void create( void ); // prototype


CreateAndDestroy first( 1 ); // global object

int main()
{
cout << " (global created before main)" << endl;

CreateAndDestroy second( 2 ); // local object


cout << " (local automatic in main)" << endl;

static CreateAndDestroy third( 3 ); // local object


cout << " (local static in main)" << endl;

create(); // call function to create objects

Computer Programming 41
Main_Program3.cpp
CreateAndDestroy fourth( 4 ); // local object
cout << " (local automatic in main)" << endl;

return 0;
}

// Function to create objects


void create( void )
{
CreateAndDestroy fifth( 5 );
cout << " (local automatic in create)" << endl;

static CreateAndDestroy sixth( 6 );


cout << " (local static in create)" << endl;

CreateAndDestroy seventh( 7 );
cout << " (local automatic in create)" << endl;

Computer Programming 42
OUTPUT
Object 1 constructor (global created before main)
Object 2 constructor (local automatic in main)
Object 3 constructor (local static in main)
Object 5 constructor (local automatic in create)
Object 6 constructor (local static in create)
Object 7 constructor (local automatic in create)
Object 7 destructor
Object 5 destructor
Object 4 constructor (local automatic in main)
Object 4 destructor
Object 2 destructor
Object 6 destructor
Object 3 destructor
Notice how the order of the
Object 1 destructor constructor and destructor
call depends on the types of
variables (automatic, global
and static) they are
associated with.
Class_Program.cpp
#include <iostream>
#include <conio>
using namespace std;

class Test{
public:
Test( int ); // constructor
~Test(); // destructor
private:
int data;

};
// Create constructor
Test::Test( int value )
{
data = value;
cout << “Constructor" << data << endl;
}
// Create destructor
Test::~Test()
{
cout << “Destructor" << data << endl;
Computer Programming 44
}
Class_Program.cpp
Test t1(1);
int main()
{
Test t2(2);

{
Test t3(3);
}

{
Test t4(4);
}

getch();
return 0;
}

Computer Programming 45
Using Data Members and Member Functions
• Classes often provide public member functions to allow
clients of the class to set (i.e., write) or get (i.e., read) the
values of private data members.

• A typical manipulation might be the adjustment of a


customer’s bank balance (e.g., a private data member
of a class BankAccount) by a member function
computeInterest.
• A member function that sets data member
interestRate would typically be named
setInterestRate, and a member function that gets
the interestRate would typically be called
getInterestRate.
Computer Programming 46
Using Data Members and Member Functions (II)

• Programmer decides what variables the


function can set and what information the
function can get.
• public set function would check
attempts to modify data members.
– ensure that the new value is appropriate for that data
item.
– For example, an attempt to set the day of the month
to 37 would be rejected.
– programmer must include these features

Computer Programming 47
Assignment by Default Memberwise Copy

• assignment operator (=) sets variables equal, i.e., x =


y;
• Can be used to assign an object to another object of the
same type.
– memberwise copy—member by member copy
• objects may be
– passed as function arguments
– returned from functions (call-by-value default).
• Use pointers for call by reference

Computer Programming 48
What is a copy constructor?

• A copy constructor is a member


function which initializes an object
using another object of the same class.

Computer Programming 49
Default.cpp
// Demonstrating that class objects can be assigned
// to each other using default memberwise copy
#include <iostream>
using namespace std;

// Simple Date class


class Date {
public:
Date( int = 1, int = 1, int = 1990 ); // default constructor
void print();

private:
int month;
int day;
int year;
};

// Simple Date constructor with no range checking


Date::Date( int m, int d, int y )
{
month = m; day = d; year = y;
}
Computer Programming 50
Default.cpp
// Print the Date in the form mm-dd-yyyy
void Date::print()
{
cout << month << '-' << day << '-' << year;
}

int main()
{
Date date1( 7, 4, 1993 ), date2; // d2 defaults to 1/1/90

cout << "date1 = ";


date1.print();
cout << "\ndate2 = ";
date2.print();
Date date3 = data1; // Copy constructor
cout << "\nCopy Constructor date3 = ";
date3.print();
date2 = date1; // assignment by default memberwise copy
cout << "\n\nAfter default memberwise copy, date2 = ";
date2.print();
return 0;
}
Computer Programming 51
OUTPUT:

date1 = 7-4-1993
date2 = 1-1-1990
Copy Constructor date3 = 7-4-1993

After default memberwise copy, date2 = 7-4-1993


Software Reusability

• People who write object-oriented programs


concentrate on implementing useful classes.
• Tremendous opportunity to capture and catalog
classes
– accessed by large segments of the programming
community
– Class libraries exist for this purpose
• Software being constructed from existing, well-
defined, carefully tested, well-documented,
portable, widely available components.
– speeds development of powerful, high-quality software
Computer Programming 53

You might also like