P. 1
Obejct Oriented Programming Lab Manual

Obejct Oriented Programming Lab Manual

5.0

|Views: 5,030|Likes:
Published by Ameen
Obejct Oriented Programming OOP Lab Manual, ECE 1201.
Obejct Oriented Programming OOP Lab Manual, ECE 1201.

More info:

Published by: Ameen on Sep 05, 2008
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as DOC, PDF, TXT or read online from Scribd
See more
See less

05/20/2013

pdf

text

original

Sections

1.1 Objective

To expose the students with Microsoft Visual C++
Integrated Development Environment (IDE)

To let the student experience coding, compiling and
debugging a simple C++ program

1.2 Introduction

Programming language which serves as the intelligent of any
computer systems has evolved tremendously since it was first developed.
Currently, in most electronic devices ranging from mobile handset to
washing machine even to cars have computer embedded system and thus
requires some form of programming language to govern the operation of
those devices.

C++ is one of the high-level language that is developed by Bjarne

Stroustrup

(his

personal

website:
http://www.research.att.com/~bs/homepage.html), of which is actually C is a
subset of C++. It is developed on basis of enabling object-oriented
programming, where you will learn and apply its concept in this subject.

1.3 Working environment

We will use Microsoft Visual C++ Integrated Development
Environment (IDE). The environment has the capability of editing,
debugging, compiling and executing C and C++ programs. In the following
sections, we will have a rapid tour in creating, compiling, performing debug
and finally executing our programs or projects. Please explore the Help
option yourself in getting used to this compiler.

1.3.1A Basic C++ Program

From time to time, you will get used to the syntax that is being
employed by C++. As long as you are familiar with C language, it will
provide you good start in understanding the syntax of C++. Observe the
following example:

1#include
2using namespace std;
3int main()
4{

//print out Welcome to OOP for Engineers to screen

14

ECE 1201: Object Oriented Programming module

5

cout<<"Welcome to OOP for Engineers"<

6

//to hold the execution window

7

system("pause");

8

return 0;

}

We will try to run this program shortly in Visual-C++.

15

ECE 1201: Object Oriented Programming module

1.3.2Creating New Source File (Single source program)

You can either create a single source file, or a project. The selection
for either one will depend on your approach of solving problem. Now, we will
demonstrate how to create a single source file.
When you select ‘New’ from the File option, a dialog box will be
opened for you (Fig 1.1). You will choose the ‘Files’ option and from there,
click to ‘C++ Source File’. Give a file name and save your file into your
own intended directory. You will write your source codes at the editor window
given for you (Fig 1.2). .

Fig. 1.1 Creating new C++ source file

16

ECE 1201: Object Oriented Programming module

Fig. 1.2 Editor window

17

ECE 1201: Object Oriented Programming module

In saving your file, mind you that you need to follow the instructions as
given in the Submission Procedure section as given in the General
Guidelines and Rules
. Compiling your program is made easy in Visual C+
+. Fig 1.3 shows you which button to click or else, you can choose the
option: Build->Compile SourceFileName.cpp. Then you will need to
perform some linking to all associated files and then an executable file of
your source code will be created. This is done by choosing Build->Build
SourceFileName.exe
(Fig. 1.4). Upon the successful completion, you can
execute the file.

Fig. 1.3 Compiling the source file

Click here!

18

ECE 1201: Object Oriented Programming module

Fig. 1.4 Creating an executable file

1.3.3Creating Project

As we proceed further in this subject, we will need to create a project
that consists of multiple files, especially when we are creating our own user-
defined data type (meaning creating ‘class’es). One application might have
more than 1 file, let’s say it comprises of some header files and source files.
You can either:

1.Create the project first, then later you will create the
header/source files and add to the project
2.Create the required files prior to creating the project
When you select ‘New’ from the File option, a dialog box will be
opened for you (Fig 1.1). You will choose the ‘Projects’ option and from
there, choose ‘Win32 Console Application’. In this subject, most of the
time, we will be creating console application where you will have your output
in MS-Dos Window. Give a name to the project name and choose a directory
to save your project. It is much easier if all files and project are in one folder.

Click here!

19

ECE 1201: Object Oriented Programming module

Fig. 1.5 (a) Creating new project

Then just click ‘Finish’ at the next dialog box that pops up Fig 1.5 (b).
Finally, click ‘OK’ at the next popped-up dialog box (Fig 1.5 (c)).

Fig. 1.5 (b) Creating new project (cont’d)

Choose this!

20

ECE 1201: Object Oriented Programming module

Fig. 1.5 (c) Creating new project (cont’d)

21

ECE 1201: Object Oriented Programming module

Provided you have created the header files and source files
individually, you will add the associated files to this project. At the left pane
of your window, you will see ‘ClassView’ and ‘FileView’. Click to the
‘FileView’. Right click to the name of your project and choose ‘Add Files to
Project’
(Fig. 1.6). Locate the directory from which you are going to include
the associated files to your application. In creating an executable version of
your project, you will choose Build->Build projectname.exe.

Fig. 1.6 Adding files to your project

Choose this!

22

ECE 1201: Object Oriented Programming module

1.4 Discussion on the basic of C++ Program

1

#include

2

using namespace std;

3

int main()

4

{

5

char course_code[10];

6

//print out Welcome to OOP for Engineers to screen

7

cout<<"Welcome to OOP for Engineers"<

8

cout<<"Input the course code for this lab:"<

9

cin>>course_code;

10

cout<<"The course code for this lab
is:"<

11

return 0;

12

}

Line
No.

Code

Explanation

1

#include

Causes C++ preprocessor to take
code existing in iostream file

2

using namespace std;

A part of the program in which
certain names are recognized;
outside of the namespace they are
unknown, hence for this purpose,
cout is contained inside std
namespace.

6

//print out Welcome to OOP for
Engineers

Single line commenting

7

cout<<"Welcome

to

OOP

for

Engineers"<<..

Print out "Welcome to OOP for
Engineers" string, similar to
printf()

7

..>>endl;

Printing single endline

11

cin>>course_code;

Input from user, similar to scanf()

12

.. lab is:"<

Observe how values of variable is
printed

1.5 Types of Errors

In writing programs, you will come across with some frightening
moments when you cannot run your program successfully. But don’t be
afraid! When you know the difference type of error, then you are able to
handle your fear, detect the error and provide correct code for it. Mind you
that you should regard writing program is just like writing an essay. Any
programming language has its own grammar, specifications and regulations
as similar to what you have known in learning any other spoken language.

23

ECE 1201: Object Oriented Programming module

Hence, the ‘syntax’ of a programming language will detail the rules for
creating a proper program in that language.

24

ECE 1201: Object Oriented Programming module

There are basically 2 types of error:
1.Syntax/compilation/compile-time error
Meaning:
Error that occurs when code statements VIOLATE the grammatical
rules of the programming language
Example:
To omit semi colon at the end of a C++ statement
Consequence:
Error message will be displayed and the program cannot be run as
long as these errors are not corrected

2.Logic/ execution/ run-time error
Meaning + Consequence:
Error that does not prevent your program from compiling
successfully but it does not give the desired results during its
execution
Example:
Error in your algorithm, any mathematical expression

1.6 Built-in Data Types

We assume at this point, you are familiar with built-in data types such as
int, double, float, char etc. It is also better that you know the size of each
data type. In C++, we also have another data type which is ‘bool’ type.
bool will only have two possibilities, true or false. True will be represented
as 1 and false will be represented as 0. This following example shows how to
use this bool variable.

1

#include

2

using namespace std;

3

int main()

4

{

5

bool isHot=1;//putting this as yes as default

6

cout<<"Is today hot? 0 for no and 1 for yes"<

7

cin>>isHot;

8

if(isHot)

9

{cout<<"Today is hot! Drink more water!"<

}

10

else

11

{cout<<"Today is cold! Wear thicker clothes!"<

12

return 0;}

25

ECE 1201: Object Oriented Programming module

1.7 Exercises

Here are some exercises to make the students familiar to the Visual C++
IDE. Follow the submission procedure.

1.7.1 Write codes

Write a program that displays the squares, cubes and fourth powers of the
numbers 1 through 5. Save the file in your directory as question1.cpp.

1.7.2 Debugging

Find errors in these lines of codes. Locate them and give the corrections.
Provide your answers in question.txt.
1

#include

2

using namespace std;

3

int main()

4

{

5

int number1=0,number2=8, value(0);

6

value=number1+number2

7

cout>>number1<<"+"<

8

return 0;

9

}

26

ECE 1201: Object Oriented Programming module

Chapter [2] : Pointers, reference, array, string class

and functions

2.1Objective

To enhance the understanding of the students about the topics
pertaining to arrays, pointers, reference, string and functions

2.2Pointer

Basic format for declaring a pointer:

data_type* pointer_name;

During initialization, you can either:
•Initialize to 0 or NULL, means pointing to nothing

•Assign to an address of a variable of same type

2.3Reference

Reference is considered as another name for a variable.

int num(5);
int& number=num;

However, if you attempt to reassign a previously declared reference
to be an alias to another variable, it will cause a logic error. Example for such
a case:

int num(5);
int& number=num;
int num3=&number;

2.4Differences between Pointers and References

Restrictions

Referenc
e

Pointe
r

It reserves a space in the memory to store
an address that it points to or reference

No

Yes

It has to be initialized when it is declared

Yes

No

It can be initialized at any time

No

Yes

Once it is initialized, it can be changed to
point to another variable of the same type

No

Yes

It has to be dereferenced to get to a value it
points to

No

Yes

It can be a NULL pointer/reference

No

Yes

It can point to another reference/pointer

No

Yes

An array of references/pointers can be No

Yes

27

ECE 1201: Object Oriented Programming module

created

Table 1: Differences between pointer and reference

28

ECE 1201: Object Oriented Programming module

2.5Static VS Dynamic Memory Allocation

Engineering problems normally require large arrays to store data for
some applications. For system of limited memory, having to specify the size
of all arrays to be used and allocating the enough memory space for them
prior to the program execution could lead to insufficient memory to run the
program. Hence, dynamic memory allocation is a way to preventing such
a problem to be occurred. In other words, whenever you need the variables,
you will create them and you can free the memory at any time in your
program whenever you think you don’t need them anymore.
In C, you use malloc() and free() for such a purpose, but for C++,
you will use new and delete operators. Table below summarizes the
differences between static and dynamic memory allocation.

Static

Dynamic

Memory space is being allocated
during compilation time

Memory space is being allocated
during run time

The amount of allocated memory is
fixed and reserved

The amount of memory is allocated
according to what is needed during
execution

The memory cannot be released until
the program terminates

The memory can be released
anytime we want, it won’t erase the
pointer, just the memory space that
it is being allocated to

Have the possibility of failure in
executing a program when it is
lacking of enough memory

More flexible in this sense, where
memory is only allocated when it is
needed

Example of creating a static pointer:

int num(4);
int* numPtr=#

Example of creating a dynamic
pointer:

int* numPtr=new int(4);

A region of memory called heap is
used for this purpose; a pool of free
memory locations that are not
being used by any program
Table 2: Differences between static and dynamic memory allocation
In using dynamic memory allocation, ‘memory leak’ problem might occur
that can cause memory resource problem. It occurs when you fail to return
the memory to the free store when it is no longer in used. Have a look at the
example given below:

1float* ptr=new float;
2*ptr=7.9;
3ptr=new float;
4*ptr=5.1;

For this example, in line 1 and 2, you have allocated memory space of

29

ECE 1201: Object Oriented Programming module

type float with value of 7.9 to ptr. Thus ptr holds the address of this block of
memory. But without releasing the memory, you reallocate another space of
type float with value of 5.1 (as seen in line 3 and 4). The first memory block
is not deleted, however the address is lost since ptr now contains the
address of the second block. Hence, the program will not be able to use the
first block eventhough it still occupies some memory space.
Hence, the solution to this problem is to always free the memory that
it has been allocated (by using delete operator) before you need to allocate
new value to the pointer.

2.6Arrays

Arrays can be of 1-D or multi dimensional type. Declaration of an array

can be done as follow:

data_type arrayName[array_size]

Examples:

char name[]={“object oriented programming”};
int value[5]={1,2,3,4,5};
float number[6];
Some issues regarding arrays:
1.You can either initialize the values for your array elements in the
initializer list for the array or perhaps later in your program.
2.If you don’t specify the size for the array and only provide the
initializer list, it’s OK. But neglecting to specify any size when you
don’t give the initializer list will cause error.
With related to topic 2.5, you can create dynamically allocated array.
The size is depending on how many values needed to be stored during run-
time. It can be specified by specifying an integer variable, an integer
constant, or an expression. Format of creating and destroy a dynamic array:

data_type pointer_name;
pointer_name=new data_type[size];
delete[] pointer_name;

Have a look at this example, which asks the user to input the size of the
array:

1

#include

2

#include

3

using namespace std;

4

int main()

5

{ int *ptr, n;

6

cout<<"Specify the size of an array to be created.."<

30

ECE 1201: Object Oriented Programming module

7

cin>>n;

8

ptr=new int[n];

9

if(!ptr)

10

{cerr<<"Memory allocation error!"; exit(1);

}

11

for(int i=0;i

12

{ ptr[i]=(i+1)*2; cout<

13

cout<

14

return 0;}

31

ECE 1201: Object Oriented Programming module

Another example below is about creating a 2-D dynamic array that also
prompts for user input.

1

#include

2

#include

3

using namespace std;

4

void memError()

5

{

cerr<<"Memory allocation error!";

6

exit(1);}

7

int main()

8

{

9

int rows,columns,i,j;

10

int** pointer;

11

cout<<"Enter a number for rows: ";

12

cin>>rows;

13

cout<<"Enter a number for columns: ";

14

cin>>columns;

15

pointer=new int*[rows];

16

if(!pointer)

17

memError();

18

for(i=0;i

19

{

20

pointer[i]=new int[columns];

21

if(!pointer)

22

memError();

23

}

24

cout<

25

for(i=0;i

26

{

27

for(j=0;j

28

{

29

pointer[i][j]=(i+1)*(j+1);

30

cout<

31

}

32

cout<

33

}

34

for(i=0;i

35

delete[] pointer[i];

36

return 0;

32

ECE 1201: Object Oriented Programming module

37

}

33

ECE 1201: Object Oriented Programming module

2.7String Class

string is another data type supported by standard C++. It eases the
user in many ways. One of its advantages is that user need not to worry
about creating an array of right size to hold string variables/values. The
string class assumes all the responsibility for memory management. In
order to use it, you must include header file.
Try to run these codes out! Can you initially guess its output?

1

#include

2

#include

3

using namespace std;

4

int main()

5

{

6

string s1("Man");

7

string s2="Beast";

8

string s3;

9

s3=s1;

10

cout<<"s3="<

11

s3="Neither "+s1+" nor ";

12

s3+=s2;

13

cout<<"s3="<

14

cout<

15

s1.swap(s2);

16

cout<

17

return 0;}
With this string data type, you can use some operators such as =,
+= and +. Observe how string variables or objects are created and
initialized in line 6, 7 and 8. Line 15 is calling swap() function from
object/variable s1, which swapping the values between s1 and s2. You will
understand this when you have covered Lab 3!
Another convenience that string class provides is during
input/output. Observe and run these lines of codes:

1

#include

2

#include

3

using namespace std;

4

int main()

5

{ string full_name, nickname, address;

6

string greeting("Hello, ");

7

cout<<"Enter your full name: ";

8

getline(cin, full_name);

34

ECE 1201: Object Oriented Programming module

9

cout<<"Your full name is "<

10

cout<<"Enter your nickname: ";

11

cin>>nickname;

12

greeting+=nickname;

13

cout<

14

cout<<"Enter your address in separate lines"<

15

cout<<"Terminate with '$'"<

16

getline(cin,address,'$');

17

cout<<"Your address is: "<

18

system("pause");

19

return 0;

20

}

This example reads the user’s name, which presumably contains
blanks, using getline(). The 1st

argument is the stream object from which

the input will come and 2nd

object is the string object where the text will be

placed.

Line 16 has 3 arguments, where the 3rd

one specifies the character to
be used to terminate the input. In this case, we use ‘$’ to be inserted by user
before ENTER is pressed. This 3rd

argument is called delimiter. If no 3rd

argument is supplied, by default, the delimiter will be \n.
Well, this class has a lot of member functions that you can utilize. You
can refer to any online documentations or reference books that further
explain about the member function.

2.8Functions

Basic format of a function prototype:

return_type function_name(argument_list)

Similar to the concept of a black box, function can be treated like a
black box where you give some input to that box and request it to perform
something in order to obtain the desired output. Hence, as the creator of the
function, one should be careful of what you are creating. Avoid from making
careless mistakes in providing the return and the arguments lists.
Common mistakes done by students that can cause syntax and

execution errors are:

1.Not passing the correct values for the parameter list. For example:
when a function requires a pointer as argument, then you have to
place ‘&’ operator before the variable name, which means you are

35

ECE 1201: Object Oriented Programming module

passing the address of the variable in calling the function. So be
sure of writing the correct syntax for such a purpose.
2.Providing a return type in function header/prototype but not
defining it inside function definition.
3.Forgetting to place semicolon at the end of function
header/prototype.
4.The function call and function prototype do not match to each

other.

36

ECE 1201: Object Oriented Programming module

Some important terminologies

These are some terminologies that you normally encounter in class,
books or website. By referring to the function given below, Table 3 gives the
associated example with its corresponding terminology.
Example function:

1double square (double side)
2{
3

return side*side;

4}

Terminologies

Example

Function header/signature

Line 1

Function prototype

double square (double)

Function definition

Line 1 to 4

Function call

double a=square(5.6);

Function parameter

double side

Table 3: Terminologies related to ‘function’ chapter

37

ECE 1201: Object Oriented Programming module

Chapter [3]: Classes and Data Abstraction

3.1

Lab Objectives

•To enhance the understanding of student about the underlying
concepts of classes
•To demonstrate the approach to build classes and create object

3.2

Introduction

You can view a class as your own customized ‘struct’ that
encapsulates data and function as well. When we encapsulate data and
function in one entity, most of the time, the function would not have to take
trouble to ask for some data to be included in its argument list, but will still
need to if it is required. So it depends on the functionality of the function
that you’re designing for the class! You will understand why when you create
your first class!

Format of a class definition:

class your_class_name
{

member_access_specifier:
data members;
member_access_specifier:
member_functions();

};

When you use cin and cout to perform I/O, you have actually created
objects from istream and ostream respectively that has been defined in
iostream header file! And also, when you create and use an object of a class
in any application, your application is known as a client/user of that class!
In contrast to what you have done in Computing Systems and Programming
subject, it is about procedural programming where it concerns more on
writing functions. However, for this subject, OOP will solve any problem
statement based on object oriented programming paradigm, where it
concerns on creating objects and deriving classes.

38

ECE 1201: Object Oriented Programming module

Fig 1: Class encapsulates data members as well as member functions.
Public member members acts as interface between class and user/client of
that class, providing some communication between these two entities by
enabling the user to retrieve and modify the private data members

Private data
members
Private
member
functions

P
u
b
lic
m
e
m
b
e
r fu
n
c
tio
n

Class

Client

39

ECE 1201: Object Oriented Programming module

3.3

Example of A Problem Statement

A bank wants you to create an application that will allow its teller to
view client information. The interface is created for you as shown below (Fig
2); you need to implement the Client class which stores the data. Once
your application is complete, the bank manager should be able to enter an
account number to view corresponding client’s information. The information
is stored in four arrays containing first names, last names, account numbers
and account balances. When the user enters the sentinel value, -1, the
application should exit.

Fig 2: Example of the execution window

3.4

Let’s Build Class Together!

3.4.1In a single source file

As for a start, you will create a class in a single source file along with
your main() function. In a single source file, class is defined before the
main() function, before you can use it to create objects. Just as you define
your functions before you call it. Execute these codes:

1#include
2using namespace std;
3class NewClass
4{ private:
5 int data1;
6 public:
7 //function to initialize data
8 void setData(int d){data1=d;
9 //function to return data
10 int getData(){return data1;}
11};
12int main()
13{
14 NewClass n;
15 return 0;

40

ECE 1201: Object Oriented Programming module

16}

Fig 3: Defining class and main() in one file

41

ECE 1201: Object Oriented Programming module

3.4.1.1

Experimenting with member functions

a)Observe the output of the program.
b)Try to call function getData() in main() function with this line of code:
cout<<"The data in your object is: "<

What do you get? What is the way to call a member function? Do we need
to pass any arguments in such a function? Why?
c)Now, try to call setData() function.

3.4.1.2

Experimenting with data members

a)In the NewClass class that you are working on now, you have 1 private
data member of type integer. Try to access your data from main()
function by writing this line of code:

cout<<"The data in your object is: "<

What do you get? And why?
b)Create a data member, data2, in public section of type int.
c)Make an attempt to access data2 by repeating the same line as given in
a) but change the name of data. Would you be able to run the code?
Why?

d)Something to think about: What is the reason of us making our data as
private and our member function as public?
e)Create a print() function that can print out the value of your data
members. Example of an output:

data1=9, data2=8

3.4.2In a multiple files

One of the fundamental principles of good software design is to
separate a class’ interface from its implementation. This concept is called
separation.

What do we mean by this? A class’ interface consists of member
function prototypes, which name the behaviours of the class and for each
provide return types and a list of parameter types. Meanwhile the
implementation consists of the code that executes when a member
function is invoked/called.

One of the way of implementing separation in OOP is to separate the
function definition into a .cpp source file. Hence, class definition will be
included inside a header file that you will create and the function definitions
are included in another source file (.cpp). Since you are dealing with multiple
files now, you need to group the files into 1 project that serves the solution
for any programming problem given to you! Remember how to create

42

ECE 1201: Object Oriented Programming module

project from your Lab 1? From the example of NewClass that we have used
earlier, we will create our first header file!

3.4.2.1

Creating class definition in a header file
a)Create a project with the name MyFirstProject.
b)Create a header file named NewClass.h and include it in this project.
c)Amend these lines of codes to the class definition.

1#ifndef NEWCLASS_H
2#define NEWCLASS_H
3class NewClass
4{

private:
5 int data1;
6 public:
7 void setData(int); //function to initialize data
8 int getData(); //function to return data
9 void print(); //function to print data
10};
11#endif

Fig 4: Defining class definition in a header file

d)Take note that NEWCLASS_H can be of any name, but to make things easier,
it is better to follow the name of header file. Line 1, 2 and 11 are pre-
processor directives that prevent including the file NewClass.h more than
once. This is to ensure that if such a header file of the same name has
been defined previously by others, the code between line 2 and 11 are
ignored. Such a way will avoid similar and duplicating codes done by you
and any other person.

3.4.2.2

Defining your member function in a .cpp file

a)Add another file to the MyFirstProject folder. Name this file as
NewClass.cpp.
b)In this file, you will give the definitions for the member function of
newclass. Include these lines of codes into the source file you’ve created.

1 #include
2 using namespace std;
3 #include "NewClass.h"
4
5 void NewClass::setData(int d) {data1=d;

}

6 int NewClass::getData(){return data1;}

43

ECE 1201: Object Oriented Programming module

7 void NewClass::print(){

cout<<"Data1="<

Fig 5: Member function definition in NewClass.cpp

c)Take note that when you define member function outside the class
definition, you NEED to AMEND class name + scope resolution operator
BEFORE the member function name, for example in this case, NewClass::.
This will ‘tie’ the member name to the class name to uniquely identify the
functions of a particular class.
d)Even though these functions are defined outside class, they are still
within that class’ scope.
e)You might also observe the using of angle brackets, <> and quotes sign,
“”, in including header files. By putting your header file inside “”, it will
tell the pre-processor that the header file is probably not within the
library of standard header files, since you might save your work in other
folder. Hence, the pre-processor will search your header file somewhere
on the disk storage (It will do the work, not you! But you only provide the
instruction for it).

3.4.2.3

Creating a driver program

a)To use your class and instantiate objects from it, you need to provide the
main() function. Hence this will also be in separate .cpp file. Create
another .cpp file with the name main.cpp
b)From the main() function as shown in Fig 6, amend the necessary line of
codes in your source file.

1#include
2using namespace std;
3#include "NewClass.h"
4int main()
5{
6NewClass n;
7return 0;
8}

Fig 4: Main driver program

3.4.2.4

Run your project

a)Save your files and project. Try to execute them.
b)Try to call the setData(), getData() and print() functions from the
main(). You might refer to what you have done in 3.4.1.1 and 3.4.1.2.

44

ECE 1201: Object Oriented Programming module

3.4.2.5

Experimenting with constructors and destructors

a)Constructor is a member function that is automatically called when we
create an object, while destructor is automatically called when the object
is out of scope.
b)Constructor is used to initialize the data members according to the
desired value.
c)In the NewClass example, previously we called the setData() if we want to
give some value to our data member. This function is called after the
instantiation of an object.
d)Referring to the NewClass class definition, you have not yet provided
both constructor and destructor. In this case, the compiler will
automatically provide default constructor
for you. Hence during the
instantiation of the object, the data member will be initialized to any
value
.

e)Can you call the setData() function to get the value of your data
member? Try this out!

45

ECE 1201: Object Oriented Programming module

f)In order to ensure that the data members will be properly initialized, one
will provide explicitly inside class definition and define it in a separate
.cpp file alongwith other function definitions (as demonstrated
previously). There are 3 types of constructor:
a.Default constructor

•This type of constructor does not have any arguments
inside its parenthesis.
•Is called when creating objects without passing any
arguments

NewClass N;

b.Constructor

•This type of constructor accepts arguments inside its
parenthesis
•Is called when creating objects without passing any
arguments

NewClass N(5);

c.Copy constructor (will be ignored for this lab)
•This constructor is called when:
1.Passing object as an argument to a function

void foo(NewClass n);

2.Return object from a function

NewClass foo();

3.Initializing an object with another object in a
declaration statement

NewClass n2;

//call default constructor

NewClass n1(n2);

//call copy constructor

NewClass n3=n2;

//call copy constructor

g)Provide these codes in the NewClass class definition to visualise how
constructor and destructor should be written. Follow the concept of
separation accordingly; i.e. write the function prototype inside the class
definition (in a header file .h) and provide the function definition inside
the separate member function definition source file (.cpp):
a.Default constructor

NewClass()
{

data1=0;
cout<< “Default constructor is called”<

}

b.Constructor with arguments

NewClass(int d)

46

ECE 1201: Object Oriented Programming module

{

data1=d;
cout<< “Constructor is called”<

}

c.Destructor

~NewClass()
{

cout<< “Destructor is called”;

}

47

ECE 1201: Object Oriented Programming module

h)In main() function, instantiate some objects with the following codes.
Observe the output.

NewClass obj1(4);
NewClass obj2;

i)Constructor with argument that you have written can also accept default
arguments, which will actually perform like a default constructor. Have a
look at this example:

NewClass(int d=0)
{

data1=d;
cout<< “Constructor is called”<

}

j)By providing many definitions for constructor, you are actually
implementing ‘function overloading’; i.e. functions of same name but
different parameters (not return type) and function definition.

3.5

Exercise

Remember the problem statement given in 3.3? You are given with all the
associated files. Now we will have to amend the codes in Client.h and
Client.cpp so that the main driver will work! Prior to that, assume:
The program has pre-defined records kept by the bank. Data
stored in the driver program:
This is just a simple interface where more enhancements could be

made.

Account
Number

First Name

Last Name

Balance
Account

1234652

John

Blue

1000.78

1234666

Sarah

White

2056.24

1234678

Jack

Red

978.65

1234681

Adam

Brown

990.00

1234690

Diane

Yellow

432.75

1234770

David

Black

780.78

1234787

Kristin

Green

4590.63

1234887

Jennifer

Orange

7910.11

1.Creating project. Create a project and include all these files; Client.h,
Client.cpp and AccountInformation.cpp.
2.Determining variables/data members for the class. Examine the
codes from AccountInformation.cpp, including all the get() function calls
that the Client object uses to retrieve information. These function calls
can be found in the displayInformation function.

48

ECE 1201: Object Oriented Programming module

3.Creating the Client header file. Switch to your Client.h file. Define 4
private data members, firstName, lastName, account and balance to
represent a first name, a last name, an account number and a balance
account. Then declare function prototypes for the default constructor and
a constructor that takes two strings, one int and one double argument, as
well as the necessary get and set functions. Each data member should
have a corresponding get and set function.

Note: get() function is to return value of data member, while set()
function is to initialize data member to the value of the passed
argument

4.Creating the Client source code file. Switch to your Client.cpp file.
Define the default constructor to use the set functions to assign 0 to the
account number and balance amount, and the empty string to the first
name and the last name. Then define the constructor that takes
arguments and assign the corresponding parameters to the appropriate
data members using the set functions.
5.Defining the get() and set() functions. Each data member should
have a corresponding get() and set() function.
6.Save, compile and run the application. Test your application to
ensure that it runs correctly by entering values at the account number
prompt to display the corresponding account record. Make sure that each
account indexed in the accountRecords array can be displayed.
7.Close the application. Close the running application by entering -1 at
the application’s prompt.
8.Close the Command Prompt window.

3.6

Summary

Data member should be grouped in private access specifier and
member functions are normally clustered together in public section.

Attempting to access private members from outside the class will cause
syntax error.

Providing a constructor to ensure every object is initialized with
meaningful values can help eliminate logic errors.

3.7

Common mistakes

Member function and data member are encapsulated in one entity. One
advantage here is that member function can access the data member
directly! As shown in previous example of NewClass class, the setData()
is defined such a way that it receives an argument that will initialize

49

ECE 1201: Object Oriented Programming module

data1:-

void NewClass::setData(int d) {

data1=d;

}

Common mistakes done by students:

void NewClass::setData(int d) {

int data1=d;}
Did you see the mistake? There’s another data1 declared in the
function! In truth, it does not have to be like this since a member
function can access data members directly without having to declare
it again inside the function body.

50

ECE 1201: Object Oriented Programming module

Forgetting to place ‘class name + scope resolution operator, ::’ when
defining member function outside class definition

Forgetting to place semicolon ‘;’ at the end of closing brace of a class
definition

Placing ‘class name + scope resolution operator ::’ at the wrong place,
for example:

NewClass::void setData(int d) {

data1=d;

}

51

ECE 1201: Object Oriented Programming module

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->