CP Week 05 06 Structures and Classes
CP Week 05 06 Structures and Classes
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;
};
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
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
};
int main()
{
Time dinnerTime; // variable of new type Time
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;
}
Computer Programming 8
Program Output
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.
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;
}
Computer Programming 15
t.printMilitary();
return 0;
}
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.
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).
Computer Programming 20
// Demonstrate errors resulting from attempts to
access private class members.
#include <iostream>
using namespace std;
Computer Programming 21
// Driver to test simple class Time
int main()
{
Time t; // instantiate object t of class Time
return 0;
}
Compiling...
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
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
return 0;
}
Computer Programming 28
Initializing Class Objects: Constructors
• constructor function - can initialize class members
– same name as the class, no return type.
Computer Programming 29
Default Constructors
• 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
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
Computer Programming 33
Main_Program2.cpp
cout << “Object t3: \n Millitary Time = ";
t3.printMilitary();
cout << "\nStandard Time = ";
t3.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
Computer Programming 37
When Constructors and Destructors Are Called (II)
Computer Programming 38
create.h
// Definition of class CreateAndDestroy.
};
#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“
int main()
{
cout << " (global created before main)" << endl;
Computer Programming 41
Main_Program3.cpp
CreateAndDestroy fourth( 4 ); // local object
cout << " (local automatic in main)" << endl;
return 0;
}
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.
Computer Programming 47
Assignment by Default Memberwise Copy
Computer Programming 48
What is a copy constructor?
Computer Programming 49
Default.cpp
// Demonstrating that class objects can be assigned
// to each other using default memberwise copy
#include <iostream>
using namespace std;
private:
int month;
int day;
int year;
};
int main()
{
Date date1( 7, 4, 1993 ), date2; // d2 defaults to 1/1/90
date1 = 7-4-1993
date2 = 1-1-1990
Copy Constructor date3 = 7-4-1993