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

UCCD1024 Lecture3 Advanced Struct Updated

The document discusses advanced data structures and encapsulation. It describes encapsulation as combining attributes and capabilities together into an abstract data type (ADT). It provides examples of structs that encapsulate attributes like name and phone number, and define capabilities like displaying information or accepting/giving money. These structs can model real-world entities and their interactions. The document also shows how to define a Circle struct that encapsulates radius and center attributes, and provides capabilities to calculate area.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
79 views

UCCD1024 Lecture3 Advanced Struct Updated

The document discusses advanced data structures and encapsulation. It describes encapsulation as combining attributes and capabilities together into an abstract data type (ADT). It provides examples of structs that encapsulate attributes like name and phone number, and define capabilities like displaying information or accepting/giving money. These structs can model real-world entities and their interactions. The document also shows how to define a Circle struct that encapsulates radius and center attributes, and provides capabilities to calculate area.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 37

UCCD1024

Data Structures And


Algorithmic Problem Solving

Lecture 3
Advanced Struct
Lecture 3: Advanced Struct
 Advanced Struct: Encapsulation
 Combining attributes and capabilities together
 Another example
 Information hiding using multiple files
 Function overloading.

L05: Object-based Programming 2


Encapsulation
 In lecture 1, we have discussed the following concept for
representation of a data structure.
 Combining the creations of (i) a data structure (type),
X, and (ii) the algorithms that manipulate X, we get
something called ADT, the abstract data type as
shown below.
 The formal term of this combination is encapsulation
that encapsulates everything related to X into one
place.
ADT of X
Data structure X
Algorithm for X

L05: Object-based Programming 3


Encapsulation
 Let this new data structure (type) X be Person as shown
below defined using ‘struct’.
 According to the concept of ADT, we can enhance X (Person)
by the actions that it can perform or activities that can take
place between objects (of this type).
 One example is shown on next page.
1 struct Person { Judy John
2 char name[20], phone[20];
3 double money;
name name
4 Person *spouse;
5 }; phone phone
6
7 main() { money money
8 Person Judy, John; spouse spouse
9

10 Judy.spouse = &John; // set spouse to be the


11 John.spouse = &Judy; // address of the desirable
12 } // object.

L05: Object-based Programming 4


Struct attributes & capabilities
 The enhanced Person type below now has 2 sections.
 The previously familiar attribute section starts from line 2.
 The new function section starts from line 5 to simulate
struct variable capabilities.
1 struct Person {
2 char name[20], phone[20]; // Attributes section
3 double money;
4 Person *spouse;

5 void type() { // capabilities section


6 cout << "\nMy name is " << name;
7 cout << "\nMy phone number is " << phone << " and I have RM" << money << "\n\n";
8 }
9 void acceptMoney(float m) { // accept input from other objects
10 money += m;
11 }
12 bool giveMoney(float borrowedSum, float &moneyGiven) {
13 if (money > borrowedSum) {
14 money -= borrowedSum;
15 moneyGiven = borrowedSum
16 return true; }
17 return false;
18 }
19 };
L05: Object-based Programming 5
Struct attributes & capabilities
 The first function ‘type’ gives a Person struct variable the capability to
display his/her name on screen.
 The second function at line 10 takes input inside the bracket to allow
a Person struct variable to accept money from other.
1 struct Person {
2 char name[20], phone[20]; // Attributes section
3 double money;
4 Person *spouse;

5 void type() { // capabilities section


6 cout << "\nMy name is " << name;
7 cout << "\nMy phone number is " << phone << " and I
8 have RM" << money << "\n\n";
9 }
10 void acceptMoney(float m) { // accept input from other objects

11 money += m;
12 }
13 bool giveMoney(float borrowedSum, float &moneyGiven) {
14 if (money > borrowedSum) {
15 money -= borrowedSum;
16 moneyGiven = borrowedSum;
17 return true; // send output to other object
18 }
return false;
}
}; Programming
L05: Object-based 6
Struct attributes & capabilities
 The operations inside this function allow a Person struct
variable to give money to other, i.e. capability to give.
 The new Person type can be used as shown on next page.

1 struct Person {
2 char name[20], phone[20]; // Attributes section
3 double money;
4 Person *spouse;
5 void type() { // capabilities section
6 cout << "\nMy name is " << name;
7 cout << "\nMy phone number is " << phone << " and I have RM" << money << "\n\n";
8 }
9 void acceptMoney(float m) { // accept input from other objects
10 money += m;
}

11 bool giveMoney(float borrowedSum, float &moneyGiven) {


12 if (money > borrowedSum) { // capable to give?
13 money -= borrowedSum; // Yes.
14 moneyGiven = borrowedSum;
15 return true; }
16 return false; // No, not able to give.
17 }
18 };
L05: Object-based Programming 7
Struct attributes & capabilities
 Lines 2 to 6 define and initialize objects Judy and John.
 Lines 7 to 20 call the capability functions defined earlier using
the ‘.’ operator.
 Wonderful finding: we are able to model person struct variable
and the interactions between them in such a short program.
1 void main() { // see file oac.cpp
2 Person Judy, John; float money;
3 strcpy(Judy.name, "Judy Jones");
4 strcpy(Judy.phone, "123456789");
5 John.money = 0;
6 Judy.money = 100;
7 Judy.type(); // display my name and info
8 Judy.acceptMoney(1000); // increase my money
9 //continue next page

L05: Object-based Programming 8


10 //if Judy don't have enough money
11 if(!Judy.giveMoney(50, money))
12 cout << "\nJudy does not have enough money to give to
13 John.\n\n";
14 else{
15 John.acceptMoney(money);
16
cout << "\nJudy has given John RM" << money << "
18
and now John has RM" << John.money << "\n\n";
19
20 }

L05: Object-based Programming 9


Lecture 3: Advanced Struct

Run
oac.cpp

Let’s see how this newer type object would look


like in MS Studio, i.e. can we see the newly
defined member names?

L05: Object-based Programming 10


Another example
 In this example, we define a new type, Circle.
 The sections of attributes and capabilities are highlighted.
 The input to and output from this type of struct variable are
also highlighted.

Output

Input

1 struct Circle {
Attributes
2 double radius;
3 double centerX, centerY;
capabilities
4 double a() { return radius*radius*PI; }
5 double area() { return a(); }
6 void setR(double r) { radius = (r >=0)? r : 0; }
7 };
L05: Object-based Programming 11
Another example
 In this example, we define a new type, Circle.
 The sections of attributes and capabilities are highlighted.
 The input to and output from this type of struct variable are
also highlighted.
 In the attribute section, we define the most important
ingredients of a circle, its radius and center.
 We also provide some of the important operations that a circle
should perform, e.g. compute its area.
1 struct Circle {
Attributes
2 double radius;
3 double centerX, centerY;
capabilities
4 double a() { return radius*radius*PI; }
5 double area() { return a(); }
6 void setR(double r) { radius = (r >=0)? r : 0; }
7 };
L05: Object-based Programming 12
Using the new type definition

 After declaration of a new type, one can create struct


variable of this type, for example as “Circle c1;” in the
main function.
 One can make full use of the service of Circle by calling
its functions, for example calling the area() at line 11.

1 struct Circle {
2 double radius;
3 double centerX, centerY;
4 double a() { return radius*radius*PI; }
5 double area() { return a(); }
6 void setR(double r) { radius = (r >=0)? r : 0; }
7 };
8 void main() {
9 Circle c1;
10 c1.setR(5);
11 cout << "Area = " << c1.area() << endl;
12 }

L05: Object-based Programming 13


What you will learn?
 Advance Struct: Encapsulation
 Combining attributes and capabilities together
 Another example
 Information hiding using multiple files
 Function overloading.

L06: Object based programming (2) 14


Information Hiding using Multiple Files

 It is non-professional to write program with just one function,


i.e. the main(). We should define and use multiple functions.
 It is also non-professional to use global variables. One should
try to use local variable as much as possible.
 It is also non-professional to have all the class definitions and
function definitions in just one file.
 Usually, each class should be defined in one separate file, and
the main() should be defined in another file.
 If we use multiple files, we can have the additional benefit of
information hiding.
 Here we will see one example and its usefulness.
 If you use only one function or one file, mark reduction will
appear in your assignment / assessment marking.

L06: Object based programming (2) 15


Information Hiding using Multiple Files

 We can hide the source code to keep our program design as


secret. (to protect our IP: intellectual property)
 We will separate our program into 3 files as shown below.
 The definition of Circle will be done in 2 files (Circle.h and
Circle.cpp).
 The symbol below represents the has-a relationship since
the statement {#include “Circle.h”} is used in both .cpp files.

Circle.h 1
Has-a relationship app.cpp has included Circle.h
#include "Circle.h" #include "Circle.h"

Circle.cpp 2
app.cpp 3
L06: Object based programming (2) 16
#include "Circle.h"

#include "Circle.h"

File 1: Circle.h: the header file void main() { // app.cpp


Circle c1, c2;
c1.setR(5); 3
cout << "Area = ";
 File Circle.h stores the minimal but necessary design of Circle. }

 It is minimal since no function body is provided.


 This file is good enough for a user program (e.g. see file 3) to
create Circle struct variable and activate (call) Circle behavior
(functions) since all the needed syntax can be found in Circle.h
1 #ifndef Circle_type // save as Circle.h 1
2 #define Circle_type
3 const double PI = 3.141592;
4 struct Circle {
5 double radius;
6 double centerX, centerY;
8 double a(); // Function prototypes
8 double area();
9 void setR(double r);
10 void add2Circles(Circle c2);
11 };
12 #endif 17
L06: Object based programming (2)
#include "Circle.h"

#include "Circle.h"

File 1: Circle.h : the header file void main() { // app.cpp


Circle c1, c2;
c1.setR(5); 3
cout << "Area = ";
 Lines 1, 2 and 12 are the usual code for any header file.
}

 They prohibit a header file to be included more than once in any


file, e.g. file 3 here attempts wrongly to include file 1 twice.
 Line 1 checks if the user defined system variable
‘Circle_type’ has not been defined.
 If not, interpretation from lines 2 to 11 will only be carried out.
1
1 #ifndef Circle_type // save as Circle.h
2 #define Circle_type
3 const double PI = 3.141592;
4 struct Circle {
5 double radius;
6 double centerX, centerY;
8 double a();
8 double area();
9 void setR(double r);
10 void add2Circles(Circle c2);
11
#endif
};
12
L06: Object based programming (2) 18
#include "Circle.h"

#include "Circle.h"

File 1: Circle.h : the header file void main() { // app.cpp


Circle c1, c2;
c1.setR(5); 3
cout << "Area = ";
 Line 2 defines a user created system variable Circle_type.
}
 Line 12 ends the definition of this header file.
 Suppose we include Circle.h twice in file 3, app.cpp.
 The first inclusion create no problem since Circle_type has
never been defined in file 3. Hence, a new type Circle will
be defined for file app.cpp.
 The next inclusion will produce no new definition of Circle
because of line 1 at Circle.h which checks for ’Circle_type’ .
1
1 #ifndef Circle_type // save as Circle.h
2 #define Circle_type
3 const double PI = 3.141592;
4 struct Circle {
5 double radius;
6 double centerX, centerY;
8 double a();
8 double area();
9 void setR(double r);
10 void add2Circles(Circle c2);
11 };

12 #endif
L06: Object based programming (2) 19
File 2: Circle.cpp source code
to be hidden
1 #include "Circle.h“ // saved as Circle.cpp
2 double Circle::a() { return radius*radius*PI; }
3 double Circle::area() { return a(); }
4 void Circle::setR(double r) { radius = (r >=0)? r : 0; }
5 void Circle::add2Circles(Circle c2) { radius += c2.radius; }

 File 1 cannot be compiled since the function definitions


are missing.
 File 2 gives the function definitions which are our secret.
 Each name here needs a heading “Circle::” to distinguish
for example “Circle::a()” to be the “a()” defined in Circle.
 Because it is possible that there is another struct
named Cylinder which also has a “a()” defined.

L06: Object based programming (2) 20


File 3: app.cpp
 Our user program, app.cpp, making use of Circle is shown
below.
 Line 2 attempts to include Circle.h more than once but no harm
will be done because of the header mechanism placed in file 1.
 The rest of the code is similar to all our previous example.
 The only difference is that we now have 3 files instead of one.

1 #include "Circle.h" // saved as app.cpp


2 #include "Circle.h" // include the header file more than once
3 void main() {
4 Circle c1, c2;
5 c1.setR(5);
6 cout << "Area = " << c1.area() << endl;
7 }

L06: Object based programming (2) 21


Relationships between files.
My code Circle.h
Has-a relationship app.cpp has included Circle.h

Circle.cpp app.cpp
User code

 In summary, we first create file Circle.h to define a new


type Circle with the minimal definitions.
 Circle.cpp, based on the included definitions in Circle.h,
completes the definition by providing the function bodies
(these are our IP [information property] we want to hide).
 app.cpp, based on the definitions from Circle.h, defines
Circle struct variables and do computation with these
variables.
L06: Object based programming (2) 22
Relationships between files.
My code Circle.h
Has-a relationship app.cpp has included Circle.h

Circle.cpp app.cpp
User code
Compile
Circle.o app.o
Linking
app.exe

 Each source file can be compiled into machine code file


separately like compiling Circle.cpp into Circle.o.
 The machine code files of Circle.o and app.o will be compiled
into one final executable program app.exe using a linking
process.
 The secret (file Circle.cpp) is not needed in the linking process.

L06: Object based programming (2) 23


Relationships between files.
My code Circle.h
Has-a relationship app.cpp has included Circle.h

Circle.cpp app.cpp
User code
Compile
Circle.o app.o
Linking
app.exe

 Developer: we who develop the idea of type Circle can make


money out of our work by selling some files to a user.
 These files are Circle.h and Circle.o.
 Our secret, the design of Circle, is mostly in Circle.cpp.
We will not send users this file.
 Next year, we modify Circle.cpp and sell again to users the
updated version of Circle just like some IT companies.
L06: Object based programming (2) 24
Relationships between files.
My code Circle.h
Has-a relationship app.cpp has included Circle.h

Circle.cpp app.cpp
User code
Compile
Circle.o app.o
Linking
app.exe

 User: Most users just want to use Circle. Their concerns are
 How expensive to get Circle.h and Circle.o?
 How to use?
 Circle.h should have contained enough information for
users to gain understanding of this type and its usage.
 It is your job to provide these information in Circle.h and
any other additional files such as user manual.
L06: Object based programming (2) 25
Lecture 3: OBP

Run files in
folder “hide”

Show the structure of these 3 source files.


Show that they can be compiled.
Show the 2 object files and the final executable.

To be professional, you should do program in a similar


fashion and not to put all code in just one file.

L06: Object based programming (2) 26


What you will learn?
 Advance Struct: Encapsulation
 Combining attributes and capabilities together
 Another example
 Information hiding using multiple files
 Function overloading.

L06: Object based programming (2) 28


Overloading: a bad idea?

L06: Object based programming (2) 29


Function overloading

 Overloading allows one name to represent two functions or


more. (See the examples below at lines 1 and 2)
 Lines 1 and 2 have the same meaning in concept but are
treated as 2 different functions by C++ since they operate
on different types of inputs

1 int square(int j) { return j * j; }


2 double square(double j) { return j * j; }
3 void main() {
4 cout << square(12) << endl;
5 cout << square(12.2) << endl;
6 }

L06: Object based programming (2) 30


Function overloading

 Similar observation: In UTAR, it is not uncommon to find 2


students having the same name, e.g. Lim Kok Meng. We
distinguish them as Lim Kok Meng (8502444A) and Lim Kok
Meng (8802123D), subscripted by their matric numbers.
 Similarly, 2 functions with the same name can be
distinguished using the type/class information inside ( ).
 Hence, the full name, as seen by a computer, is not just
square, but square(int) or square(double) in the example. No
ambiguity in distinguishing these two by the compiler.

1 int square(int j) { return j * j; }


2 double square(double j) { return j * j; }

L06: Object based programming (2) 31


Function overloading

1 int square(int j) { return j * j; }


2 double square(double j) { return j * j; }
3 void main() {
4 cout << square(12) << endl;
5 cout << square(12.2) << endl;
6 }

 Hence, in the example here, line 4 is calling the function


defined in line 1 since the input parameter to square() is
an integer.
 Similarly, line 5 is calling the function defined in line 2.
 There is no ambiguity.

L06: Object based programming (2) 32


Constructor

 A constructor function is used to initialize the field of a


struct variable after it is allocated a piece of memory.
 A default constructor, take no input parameter.
 We can have more constructor definitions (using
overloading) if there is a need.
 We can also have no constructor definition. The
compiler will then supply a default constructor but it will
not do any initialization.
 A constructor name must be the same as the struct
name. It has special syntax too, i.e. it has no return type.
 Refer to folder constructor for example.

L05: Object-based Programming 33


Summary
We have covered the followings:
 Employ user-defined type to define an object type with
encapsulation of attributes and functions. The functions
simulate object capabilities.
 Example
1 struct Person {
2 char name[20], phone[20]; // Attributes section
3 double money;
4 Person *spouse;

5 void type() { // capabilities section


6 cout << "My name is " << name << endl;
7 };
8 };

L05: Object-based Programming 34


Summary

Information hiding (of Circle secret) using multiple files

Circle.h 1
Has-a relationship app.cpp has included Circle.h
#include "Circle.h" #include "Circle.h"

Circle.cpp 2
app.cpp 3

 File Circle.h gives the minimal but necessary design of Circle.


 File Circle.cpp gives the function definitions which are our
secret not to be given away.
 File app.cpp is user program making use of Circle.h. It can be
compiled without Circle.cpp. It somehow needs Circle.obj, the
compiled version (in machine code) of Circle.cpp.

L06: Object based programming (2) 35


Summary

 Function Overloading
 Overloading allows one name to represent two
functions or more.

 Constructor Function
 A constructor function is used to initialize the field of a
struct variable after it is allocated a piece of memory.

L05: Object-based Programming 36


Next lecture

 We will cover Linked list in next lecture

L05: Object-based Programming 37

You might also like