Object-oriented Programming:

advertisement
Object-oriented Programming:
In OOP we deal with classes of objects. A class of objects is an open-ended set of
objects that behave in a similar way. We call these objects instances of the class.
For example, we have a class Card, which represents cards in an ordinary deck of
playing cards. Each particular card is an object, which is an instance of the class
Card.
Stucts and classes are almost identical. The only difference is that in structs the
member functions and variables (and other members) are by default public,
whereas in classes they are by default private.
In both cases you can declare them to be either public or private explicitly.
C++ is an OOPL (obj-or. prog. lang.) built on top of the C language. One result of
this is that C++ has a lot of historical baggage that it has inherited from C (includes
structs, C-arrays, C-strings, etc.).
An important programming principle was developed around 1980:
The Information Hiding Principle:
The user of a module (e.g., a class) should have all the information required to use
that module correctly and nothing more.
The implementer of a module should have all the information required to implement
that module correctly and nothing more.
This is not about proprietary information, trade secrets, military secrets, or
anything like that. What it is about is what information can be used in what parts of
the program.
The user of a module might know all about its implementation, but can't make use
of that information in the parts of the program that use the module.
The implementer of a module might know all about how it will be used, but can't
make use of that information in the part of the program that implements the
module.
This makes it very clear what the user and the implementer can depend on, and
what they should not depend on (because it might change). It's a kind of
"contract." The goal is to improve program maintenance.
We have been using classes that are good examples of this: vector, string,
iostream, cmath, ...
You (collectively, implementers and users) have to agree on what should be public
and what private.
Complex Numbers example:
Typically we write a complex number in the form x + yi, where i is the square root
of -1.
It's easier to add complex numbers in Cartesian form, and it's easier to multiply
them in polar form.
But it's the same complex number; it's just two different ways of writing it.
We have integers in C++ and we have doubles (real numbers) in C++. For scientific
and engineering applications it would also be useful to have complex numbers, but
they're not built into C++. However we can extend C++ by defining a complex
class.
Suppose a = x + yi, and b = u + vi,
then a + b = (x + yi) + (u + vi) = (x + u) + (y + v)i
Suppse a = r e^(iu) and b = s ^(iv),
then ab = (rs) e^(i(u+v))
Download