Lecture 1 H.oop-Intro
Lecture 1 H.oop-Intro
COMP2012: Introduction
Gary Chan
Brian Mak
Desmond Tsoi
In this course, you will learn the essence of OOP with some new
C++ constructs with an aim to write large softwares.
int main()
{
int k = 1;
printf("%d\t%d\n", k, func(k));
return 0;
}
struct Airplane
{
int altitude; // in meters
int speed; // in km/h
};
Question
With the loose relationship between data and codes in PP, how
can the constraints be enforced?
Data/State Consistency:
Each time we change the value of a member of an Airplane
structure, make sure that the new value is valid with respect
to the values of other members.
A snapshot of the values of all data members of an object
represents the state of the object.
Ensuring data consistency is one of the major challenges in
(large) software projects.
The problem becomes even more difficult when the program is
modified and new constraints are added.
struct Airplane
{
int altitude;
int speed;
};
For this to work, the rest of the program must use only these
functions to change an Airplane state, rather than changing
the members directly.
If we now modify the Airplane structure, then we only have to
modify the restricted set of functions that directly access the
Airplane members, and make sure they don’t violate the new
constraints.
Since we don’t access the Airplane members directly in the
rest of the program, we don’t have to worry about keeping the
data consistent.
But how can we make sure that the Airplane members are
only accessed by the restricted set of functions?
In procedural programming, we can’t . . . .
class Airplane
{
public:
int set_speed(int new_speed);
int set_altitude(int new_altitude);
private:
int altitude;
int speed;
};
void some_function()
{
Airplane B747;
B747.set_speed(340);
B747.set_altitude(1500);
B747.speed = 3441873923; // Error: speed is private!
}
———————————————————–
class Airplane
{
public:
int get_speed() { return speed; }
int get_altitude() { return altitude; }
void set_speed(int x) { speed = x; }
void set_altitude(int x) { altitude = x; }
private:
int speed;
int altitude;
};
{gchan, mak, desmond}@cse.ust.hk COMP2012 (Spring 2018) p.15
Supports Needed in OOP Languages
generic programming
data structures
more about linked list
binary search tree
hashing table
Reusable Code
It is a dream that a piece of software code is like a Lego block, and
one builds a large program like building toys with Lego blocks.
Generic Programming
Programming with types as parameters so that a function may
apply for many different types of data.
e.g. One single sorting function for int, float, Airplanes, etc.
When properly applied, OOP and generic programming can
help a lot in writing reusable codes.