Download as pdf or txt
Download as pdf or txt
You are on page 1of 32

OOP Course Al-Balqa

Applied Unviversity

CLASSES
1. Classes and structures can be used almost identically in C++. The difference
between the two is in the default accessibility associated with the members of
each (to be discussed later).
a) Members are public by default in structs.
b) Members are private by default in classes.

2. Classes enable the programmer to model objects that have attributes


(represented as data members) and behaviors or operations (represented as
member functions).

3. A C++ class declaration consists of any number of member functions, data


members (objects), and access modes (private, public or protected). The
following general form for a class declaration is:

class class-name {
public:
member-function-prototypes
private:
data-members
};

a) The member-function-prototypes after the access mode public


represent the operations.
b) The data-members after access mode private are the objects that store
the state.
c) Member functions can be private and data members can be public. The
accepted standard is to make data members private as much as possible
and to allow access to the private data members via public member
functions.

4. Member functions are sometimes called methods in other object-oriented


programming languages, and are invoked in response to messages sent to an
object. A message corresponds to a member-function call.

1
OOP Course Al-Balqa
Applied Unviversity

CLASSES (CONTINUED)

5. Example of a class definition:

class Time {
public:
Time();
void setTime(int, int, int);
void printMilitary();
void printStandard();
private:
int hour;
int minute;
int second;
};

a) Definition begins with the keyword class.


b) The body of the class definition is delineated with left and right braces.
c) The class definition terminates with a semicolon.
d) The definition contains the three integer members hour, minute, and
second.
e) The public: and private: labels are called member access specifiers.
i) Any data member or member function declared after member
access specifier public: (and before the next member access
specifier) is accessible wherever the program has access to an
object of class Time.
ii) Any data member or member function declared after member
access specifier private: (and up to the next member access
specifier) is accessible only to member functions of the class
(and friend functions).
iii) Member access specifiers always end with a colon (:) and can
appear multiple times and in any order in a class definition.
a) Use each member access specifier only once in a class
definition for clarity and readability.
b) Place public members first where they are easy to locate.

2
OOP Course Al-Balqa
Applied Unviversity

CLASSES (CONTINUED)

f) The class definition contains prototypes for the following four member
functions after the public member access specifier -- Time, setTime,
printMilitary, and printStandard.
a) These are the public member functions, or public
services or interface of the class.
b) These functions will be used by clients (i.e. portions of a
program that are users) of the class to manipulate the data
of the class.
g) The member function with the same name as the class is called a
constructor function of that class.
i) A constructor is a special member function that initializes the
data members of a class object.
ii) A class's constructor function is called automatically when an
object of the class is created.
iii) It is common to have several constructors for a class; this is
accomplished through function overloading.
h) The three integer members appear after the private member access
specifier.
i) These data members of the class are only accessible to member
functions (and, to be discussed later, "friends" of the class).
ii) Data members are normally listed in the private portion of a
class and member functions are normally listed in the public
portion.

6. Once the class has been defined, the class name becomes a new type specifier
and can be used as a type in declarations as follows:
a) Time sunset; // object of type Time
b) Time arrayOfTimes[5]; // array of Time objects
c) Time *pointerToTime; // pointer to a Time object
d) Time &dinnerTime = sunset; // reference to (alias of) a Time object

3
OOP Course Al-Balqa
Applied Unviversity

CLASSES (CONTINUED)

7. The full implementation of member functions typically includes the following


items:
a) The member function's declared return type.
b) The class name.
c) The C++ scope resolution operator :: (two consecutive colons).
d) The member function name.
e) The parameters contained between two parentheses.
f) A block that delimits the statements of the member function.
g) Syntax:

return-type class-name :: member-function-name (parameter-list)


{
declarations
statements
}

8. The following is a listing of the file which contains the specification (i.e. the
definition of the class), the implementation (i.e. the definition of the functions
contained in the class) of the class Time, and the client routine (the driver or
main() program):
a) Note the Time constructor which initializes the data members to 0 (the
military time equivalent of 12 AM).
i) This ensure that the object is in a consistent state when it is
created.
ii) Invalid values cannot be stored in the data members of a Time
object because the constructor is automatically called when the
Time object is created and all subsequent attempts by a client to
modify the data members are scrutinized by the function
setTime.
b) Member functions can be defined inside a class, but it is a good
programming practice to define the functions outside the class
definition.

4
OOP Course Al-Balqa
Applied Unviversity

CLASSES (CONTINUED)

c) Note the use of the scope resolution operator (::) in each member
function definition following the class definition.
i) Once a class is defined and its member functions are declared,
the member functions must be defined.
ii) Each member function of the class can be defined directly in the
class specification (rather than including the function prototype
of the class), or the member function can be defined after the
class body.
a) When a member function is defined outside of its
corresponding class definition, the function name is
preceded by the class name and the scope resolution
operator (::).
b) Because different classes can have the same member
names, the scope resolution operator "ties" the member
name to the class name to uniquely identify the member
functions of a particular class. The member function is
considered to be within that class's scope.
d) If a member function is defined in a class definition, the member
function is automatically inlined. Member functions defined outside a
class definition may be made inline by explicitly using the keyword
inline. The compiler reserves the right not to inline any function.

5
OOP Course Al-Balqa
Applied Unviversity

CLASSES (CONTINUED)

// Time class.
#include <iostream.h>

// Time abstract data type (ADT) definition


class Time {
public:
Time(); // constructor
void setTime(int, int, int); // set hour, minute and 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; }

// Set a new Time value using military time. Perform validity


// checks on the data values. Set invalid values to zero.
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 << ":"
<< (second < 10 ? "0" : "") << second;
}

6
OOP Course Al-Balqa
Applied Unviversity

CLASSES (CONTINUED)

// 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");
}

// Driver to test simple class Time


main()
{
Time t; // instantiate object t of class Time

cout << "The initial military time is ";


t.printMilitary();
cout << endl << "The initial standard time is ";
t.printStandard();

t.setTime(13, 27, 6);


cout << endl << endl << "Military time after setTime is ";
t.printMilitary();
cout << endl << "Standard time after setTime is ";
t.printStandard();

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


cout << endl << endl << "After attempting invalid settings:"
<< endl << "Military time: ";
t.printMilitary();
cout << endl << "Standard time: ";
t.printStandard();
cout << endl;
return 0;
}

7
OOP Course Al-Balqa
Applied Unviversity

CLASSES (CONTINUED)

Output is:

The initial military time is 00:00:00


The initial standard time 12:00:00 AM

Military time after setTime is 13:27:06


Standard time after setTime is 1:27:06 PM

After attempting invalid settings:


Military time: 00:00:00
Standard time: 12:00:00 AM

8
OOP Course Al-Balqa
Applied Unviversity

CLASS SCOPE AND ACCESSING CLASS MEMBERS

1. A class's data members (variables declared in the class definition) and


member functions (functions declared in the class definition) belong to that
class's scope. Nonmember functions are defined at file scope.

2. Within a class's scope, class members are immediately accessible by all of


that class's member functions and can be referenced simply by name.

3. Outside a class's scope, class members are referenced through either an


object name, a reference to an object, or a pointer to an object.

4. Member functions of a class can be overloaded, but only by other member


functions of the class. To overload a member function:
a) Provide in the class definition a prototype for each version of the
overloaded function
b) Provide a separate function definition for each version of the function.

5. Member functions have function scope within a class--variables defined in a


member function are known only to that function.
a) If a member function defines a variable with the same name as a
variable with class scope, the class-scope variable is hidden by the
function-scope variable. Such a hidden variable can be accessed via
the scope resolution operator by preceding the operator with the class
name.

9
OOP Course Al-Balqa
Applied Unviversity

CLASS SCOPE AND ACCESSING CLASS MEMBERS (CONTINUED)

b) Hidden global variables can be accessed with the unary scope


resolution operator.

// Using the unary scope resolution operator


#include <iostream.h>

float value = 1.2345;

main()
{
int value = 7;

cout << "Local value = " << value << endl


<< "Global value = " << ::value << endl;

return 0;
}

Output is:

Local value = 7
Global value = 1.2345

6. The operators used to access class members are identical to the operators
used to access structure members.
a) The dot member selection operator (.) is combined with an object's
name or with a reference to an object to access the object's members.
b) The arrow member selection operator (->) is combined with a pointer
to an object to access that object's members.

7. The following program:


a) Uses a simple class called Count with:
i) Public data member x of type int.
ii) Public member function print to illustrate accessing the members
of a class with the member selection operators.

10
OOP Course Al-Balqa
Applied Unviversity

CLASS SCOPE AND ACCESSING CLASS MEMBERS (CONTINUED)

b) Instantiates three variables related to type Count:


i) counter.
ii) counterRef -- a reference to a Count object
a) Declared to reference counter.
iii) counterPtr -- a pointer to a Count object
a) Declared to point to counter.
c) Note that data member x has been made public here simply to
demonstrate how public members are accessed. Data is typically made
private.

// Demonstrating the class member access operators . and ->


// CAUTION: AVOID PUBLIC DATA!
#include <iostream.h>

// Simple class Count


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

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

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

11
OOP Course Al-Balqa
Applied Unviversity

CLASS SCOPE AND ACCESSING CLASS MEMBERS (CONTINUED)

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

Output is:

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

12
OOP Course Al-Balqa
Applied Unviversity

SEPARATING INTERFACE FROM IMPLEMENTATION

1. One of the most fundamental principles of good software engineering is to


separate interface (specification) from implementation.
a) Makes it easier to modify programs.
b) As far as clients of a class are concerned, changes in the class's
implementation do not affect the client as long as the class's interface
originally provided to the client is unchanged (the class's functionality
could be expanded beyond the original interface).
c) Encourages independent software vendors (ISVs) to provide class
libraries for sale or license.

2. When building a C++ program:


a) Each class definition is normally placed in a header file.
b) The corresponding class's member function definitions are placed in
source-code files of the same name.
c) The header files are included (via #include) in each file in which the
class is used.
d) The source-code file is compiled and linked with the file containing the
main program.
e) Compilation and linkage of programs consisting of multiple source files
is compiler dependent.

3. The following program example:


a) Consists of:
i) The header file time1.h in which class Time is declared
ii) The file time1.cpp in which the member functions of class Time
are defined.
iii) The file Fig6_5.cpp in which function main is defined.
b) The class declaration is enclosed between #ifndef and #endif
preprocessor code. If prevents the code between the #ifndef and
#endif from being included if the name TIME1_H has been defined.
i) If the header has not been included previously in a file, the name
TIME1_H is defined by the #define directive and the header file
statements are included.
ii) If the header has been included previously, TIME1_H is defined
already and the header file is not included again.

13
OOP Course Al-Balqa
Applied Unviversity

SEPARATING INTERFACE FROM IMPLEMENTATION (CONTINUED)

// 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

// Time abstract data type definition


class Time {
public:
Time(); // constructor
void setTime(int, int, int); // set hour, minute and 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
};

#endif

14
OOP Course Al-Balqa
Applied Unviversity

SEPARATING INTERFACE FROM IMPLEMENTATION (CONTINUED)

// TIME1.CPP
// Member function definitions for Time class.

#include <iostream.h>
#include "time1.h"

// Time constructor initializes each data member to zero.


// Ensures all Time objects start in a consistent state.
Time::Time() { hour = minute = second = 0; }

// Set a new Time value using military time.


// Perform validity checks on the data values.
// Set invalid values to zero (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 << ":"
<< (second < 10 ? "0" : "") << second;
}

// 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");
}

15
OOP Course Al-Balqa
Applied Unviversity

SEPARATING INTERFACE FROM IMPLEMENTATION (CONTINUED)

// FIG6_5.CPP
// Driver for Time1 class
// NOTE: Compile with TIME1.CPP
#include <iostream.h>
#include "time1.h"

// Driver to test simple class Time


main()
{
Time t; // instantiate object t of class time

cout << "The initial military time is ";


t.printMilitary();
cout << endl << "The initial standard time is ";
t.printStandard();

t.setTime(13, 27, 6);


cout << endl << endl << "Military time after setTime is ";
t.printMilitary();
cout << endl << "Standard time after setTime is ";
t.printStandard();

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


cout << endl << endl << "After attempting invalid settings:"
<< endl << "Military time: ";
t.printMilitary();
cout << endl << "Standard time: ";
t.printStandard();
cout << endl;
return 0;
}

16
OOP Course Al-Balqa
Applied Unviversity

CONTROLLING ACCESS TO MEMBERS

1. The member access specifiers public and private (and, to be discussed later,
protected) are used to control access to a class's data members and member
functions.
a) The default access mode for classes is private so all members after the
class header and before the first label are private.
b) After each label, the mode that was invoked by that label applies until
the next label or until the terminating right brace (}) of the class
definition.
c) The labels public, private, and protected may be repeated but such
usage is rare and can be confusing.

2. Private class members can be accessed only by member functions (and friend
functions) of that class.

3. Public members of a class may be accessed by any function in the program.

4. Public vs. private:


a) The primary purpose of public members is to present to the class's
clients a view of the services the class provides. This set of services
forms the public interface of the class.
b) The private members of a class as well as the definitions of its public
member functions are not accessible to the clients of a class. These
components form the implementation of the class.
i) The client of a class may be a member function of another class
or it may be a global function.

5. Try to keep all of the data members of a class private. Provide public
member functions to set the values of private data members and to get the
values of private data members. This architecture:
a) Helps hide the implementation of a class from its clients, which
reduces bugs.
b) Improves program modifiability.

17
OOP Course Al-Balqa
Applied Unviversity

CONTROLLING ACCESS TO MEMBERS (CONTINUED)

6. Access to a class's private data should be carefully controlled by the use of


member functions, called access functions.
a) Access functions can read or display data.
b) Another common use for access functions is to test the truth or falsity
of conditions--such functions are often called predicate functions.
i) An example of a predicate function would be an isEmpty
function for any container class (a class capable of holding many
objects) such as a linked list.

7. A mutator function is a member function that modifies one or more data


members.

8. A utility function is a private member function that supports the operation of


the class's public member functions. Utility functions are not part of a class's
interface and are not intended to be used by clients of a class.

9. Despite the fact that public and private labels may be repeated and
intermixed, list all the public members of a class first in one group and then
list all the private members in another group. This focuses the client's
attention on the class's public interface rather than on the class's
implementation.

10. The default access for struct members is public. Access to members of a
struct also may be explicitly set to public, protected, or private.

11. The following program example:


a) Demonstrates that private class members are only accessible through
the public class interface using public member function.
b) When the program is compiled, the compiler generates two errors
stating that the private member specified in each statement is not
accessible.
c) Program includes time1.h and is compiled with time1.cpp.

18
OOP Course Al-Balqa
Applied Unviversity

CONTROLLING ACCESS TO MEMBERS (CONTINUED)

// Demonstrate errors resulting from attempts


// to access private class members.
#include <iostream.h>
#include "time1.h"

main()
{
Time t;

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


t.hour = 7;

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


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

return 0;
}

19
OOP Course Al-Balqa
Applied Unviversity

INITIALIZING CLASS OBJECTS: CONSTRUCTORS

1. When an object is created (aka instantiated), its members can be initialized by


a constructor function.
a) A constructor is a class member function with the same name as the
class.
b) The programmer provides the constructor which is invoked
automatically each time an object of the class is created (instantiated).
c) Data members of a class cannot be initialized in the class definition.
Data members must either be:
i) Initialized in a constructor of the class, or
ii) Their values may be set later after the object is created.
d) Constructors cannot specify return type or return values.
e) Constructors may be overloaded to provide a variety of means for
initializing objects of a class.

2. Constructors can contain default arguments.


a) By providing default arguments to the constructor, even if no values are
provided in a constructor call, the object is still guaranteed to be in a
consistent state due to the default arguments.
b) A programmer-supplied constructor that defaults all its arguments (or
requires no arguments) is also a default constructor, i.e. a constructor
that can be invoked with no arguments.
i) There can only be one default constructor per class.
ii) If no constructor is defined for a class, the compiler creates a
default constructor.
a) Such a constructor does not perform any initialization, so
when the object is created, it is not guaranteed to be in a
consistent state.
c) A good programming practice is to declare default arguments only in
the function prototype within the class definition in the header file.
d) Specifying default initializers for the same member function in both a
header file and the member function definition will cause a
programming error.

20
OOP Course Al-Balqa
Applied Unviversity

INITIALIZING CLASS OBJECTS: CONSTRUCTORS (CONTINUED)

3. In the following program:


a) The Time constructor function includes default arguments of zero for
each variable.
b) The constructor calls member function setTime with the values passed
to the constructor (or the default values) to ensure that:
i) The value supplied for hour is in the range 0 to 23.
ii) The values for minute and second are each in the range 0 to 59.
iii) If a value is out of range, it is set to zero by setTime.
c) The program initializes five Time objects:
i) One with all three arguments defaulted in the constructor call.
ii) One with one argument specified.
iii) One with two arguments specified.
iv) One with three arguments specified.
v) One with three invalid arguments specified.

// TIME2.H
// Declaration of the Time class.
// Member functions defined in TIME2.CPP
// prevent multiple inclusions of header file
#ifndef TIME2_H
#define TIME2_H

class Time {
public:
Time(int = 0, int = 0, int = 0); // default constructor
void setTime(int, int, int);
void printMilitary();
void printStandard();

private:
int hour;
int minute;
int second;
};

#endif

21
OOP Course Al-Balqa
Applied Unviversity

INITIALIZING CLASS OBJECTS: CONSTRUCTORS (CONTINUED)

// TIME2.CPP
// Member function definitions for Time class.

#include <iostream.h>
#include "time2.h"

// Constructor function to initialize private data.


// Default values are 0 (see class definition).
Time::Time(int hr, int min, int sec)
{ setTime(hr, min, sec); }

// Set values of hour, minute, and second.


// Invalid values are set to 0.
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;
}

// Display time in military format: HH:MM:SS


void Time::printMilitary()
{
cout << (hour < 10 ? "0" : "") << hour << ":"
<< (minute < 10 ? "0" : "") << minute << ":"
<< (second < 10 ? "0" : "") << second;
}

// Display time in standard format: HH:MM:SS AM (or PM)


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

22
OOP Course Al-Balqa
Applied Unviversity

INITIALIZING CLASS OBJECTS: CONSTRUCTORS (CONTINUED)

// Demonstrating a default constructor function for class Time.


#include <iostream.h>
#include "time2.h"

main()
{
Time t1, t2(2), t3(21, 34), t4(12, 25, 42), t5(27, 74, 99);

cout << "Constructed with:" << endl


<< "all arguments defaulted:" << endl << " ";
t1.printMilitary();
cout << endl << " ";
t1.printStandard();

cout << endl << "hour specified; minute and second defaulted:" << endl << " ";
t2.printMilitary();
cout << endl << " ";
t2.printStandard();

cout << endl << "hour and minute specified; second defaulted:" << endl << " ";
t3.printMilitary();
cout << endl << " ";
t3.printStandard();

cout << endl << "hour, minute, and second specified:" << endl << " ";
t4.printMilitary();
cout << endl << " ";
t4.printStandard();

cout << endl << "all invalid values specified:" << endl << " ";
t5.printMilitary();
cout << endl << " ";
t5.printStandard();
cout << endl;
return 0;
}

23
OOP Course Al-Balqa
Applied Unviversity

INITIALIZING CLASS OBJECTS: CONSTRUCTORS (CONTINUED)

Output is:

Constructed with:
all arguments defaulted:
00:00:00
12:00:00 AM
hour specified; minute and second defaulted:
02:00:00
2:00:00 AM
hour and minute specified; second defaulted:
21:34:00
9:34:00 PM
hour, minute, and second specified:
12:25:42
12:25:42 PM
all invalid values specified:
00:00:00
12:00:00 AM

24
OOP Course Al-Balqa
Applied Unviversity

DESTRUCTORS

1. A destructor is a special member function of a class.


a) The name of the destructor for a class is the tilde (~) character
followed by the class name.
b) A class's destructor is called when an object is destroyed, e.g. when
program execution leaves the scope in which an object of that class
was instantiated.
c) The destructor itself does not actually destroy the object.
i) It performs termination housekeeping before the system reclaims
the object's memory space so that it may be used to hold new
objects.
d) A destructor receives no parameters and returns no value.
e) A class may have only one destructor.
i) Destructor overloading is not allowed.
f) Destructors are rarely used with simple classes.
i) Destructors are appropriate for classes whose objects contain
dynamically allocated storage (e.g. for arrays and strings).

25
OOP Course Al-Balqa
Applied Unviversity

WHEN CONSTRUCTORS AND DESTRUCTORS ARE CALLED

1. Constructors and destructors are called automatically.

2. The order in which these function calls are made depends on the order in
which execution enters and leaves the scope in which objects are instantiated.

3. Generally, destructor calls are made in the reverse order of the constructor
calls.
a) Global scope:
i) Constructors are called for objects declared in global scope
before any other function (including main) in that file begins
execution.
ii) The corresponding destructors are called when main terminates
or the exit function is called.
b) Local objects:
i) Constructors are called for automatic local objects when
execution reaches the point where the objects are declared.
ii) The corresponding destructors are called when the objects leave
scope (i.e. the block in which they are declared is exited).
c) Static local objects:
i) Constructors are called for static local objects once when
execution reaches the point where the objects are first declared.
ii) Corresponding destructors are called when main terminates or
the exit function is called.

4. The following program demonstrates the order in which constructors and


destructors are called for objects of type CreateAndDestroy in several scopes:

26
OOP Course Al-Balqa
Applied Unviversity

WHEN CONSTRUCTORS AND DESTRUCTORS ARE CALLED


(CONTINUED)

// CREATE.H
// Definition of class CreateAndDestroy.
// Member functions defined in CREATE.CPP.

#ifndef CREATE_H
#define CREATE_H

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

#endif

---------------------------------------------------------------------------------------------------

// CREATE.CPP
// Member function definitions for class CreateAndDestroy
#include <iostream.h>
#include "create.h"

CreateAndDestroy::CreateAndDestroy(int value)
{
data = value;
cout << "Object " << data << " constructor";
}

CreateAndDestroy::~CreateAndDestroy()
{ cout << "Object " << data << " destructor " << endl; }

27
OOP Course Al-Balqa
Applied Unviversity

WHEN CONSTRUCTORS AND DESTRUCTORS ARE CALLED


(CONTINUED)

// Demonstrating the order in which constructors and destructors are called.


#include <iostream.h>
#include "create.h"

void create(void); // prototype

CreateAndDestroy first(1); // global object

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

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

28
OOP Course Al-Balqa
Applied Unviversity

WHEN CONSTRUCTORS AND DESTRUCTORS ARE CALLED


(CONTINUED)

Output is:

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
Object 1 destructor

29
OOP Course Al-Balqa
Applied Unviversity

ASSIGNMENT BY DEFAULT MEMBERWISE COPY

1. The assignment operator (=) is used to assign an object to another object of


the same type.

2. Such assignment is normally performed by memberwise copy--each member


of one object is copied individually to the same member in another object.

3. Memberwise copy can cause serious problems when used with a class whose
data members contain dynamically allocated storage.

4. A default memberwise copy (=) is provided by the compiler but it is


recommended that you code your own assignment operator function.

5. Example of a program that uses default memberwise copy:

// Demonstrating that class objects can be assigned


// to each other using default memberwise copy
#include <iostream.h>

// 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;
}

30
OOP Course Al-Balqa
Applied Unviversity

ASSIGNMENT BY DEFAULT MEMBERWISE COPY (CONTINUED)

// Print the Date in the form mm-dd-yyyy


void Date::print()
{ cout << month << '-' << day << '-' << year; }

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

cout << "date1 = ";


date1.print();
cout << endl << "date2 = ";
date2.print();

date2 = date1; // assignment by default memberwise copy


cout << endl << endl
<< "After default memberwise copy, date2 = ";
date2.print();
cout << endl;

return 0;
}

Output is:

date1 = 7-4-1993
date2 = 1-1-1990

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

31
OOP Course Al-Balqa
Applied Unviversity

BIBLIOGRAPHY

Barkakati, Nabajyoti, Borland C++ 4 Developer's Guide, Indianapolis, Indiana:


SAMS Publishing, 1994.

Cantu, Marco and Steve Tendon, Borland C++ 4.0 Object-Oriented Programming,
New York: Random House, 1994.

Deitel, H.M. and P.J. Deitel, C++ How to Program, Second Edition, Eaglewood
Cliffs, New Jersey: Prentice Hall, 1998.

Foster, L.S., C by Discovery, Second Edition, El Granada, CA: Scott/Jones Inc.,


Publishers, 1994.

Gorlen, Keith E., Sanford M. Orlow, and Perry S. Plexico, Data Abstraction and
Object-Oriented Programming in C++, New York: John Wiley & Sons, 1991.

Horstmann, Cay S., Mastering Object-Oriented Design in C++, New York, NY:
John Wiley & Sons, Inc., 1995.

Savitch, Walter, Problem Solving with C++, Second Edition, Menlo Park, Ca.:
Addison-Wesley Publishing Company, Inc., 1999.

Swan, Tom, Mastering Borland C++ 4.5, Second Edition, Indianapolis, Indiana:
SAMS, 1995.

32

You might also like