04-06-2012, 12:17 PM
Object-Oriented Programming
Object-Oriented Programming.ppt (Size: 70.5 KB / Downloads: 173)
The Evolution of The Notion of Object
In C, a struct models what a thing has/is (i.e., the data, also called the characteristics), but not what it does (its behavior, represented by functions).
The functions are outside and separate from structs.
In C++, the characteristics and behavior are integrated into a single structure, called object.
The data type of an object is the class of the object
The packaging of the data and the functions into a class type is called data encapsulation.
Problems with structs
Need a different struct for each different data type to be pushed onto or popped off the stack
Overflow (although it can be fixed in C, using dynamic data allocation)
The overall structure does not convey a tight coupling between the stack data and the stack operations
Definition of Classes and Objects
A new data type defined with struct (where the data and functions are together) is called a class.
Example: the data type stack is a class
Indeed, C++ has a new reserved word, class, that is synonymous to struct (except for a minor difference explained later)
Any variable of the type defined by struct or class is called an object or instance of that class
Example: In the declaration: stack S;, S is an object of the stack class.
Definition of Members
The declared variables inside structs are called the data fields in C.
In C++, the declared variables and functions inside structs/classes are called members:
member variables
member functions (also called methods)
Data Hiding: Context
Note that users of a stack object can access directly the members data[] and top
For example, a user can do:
But notice that the 3 stack operations are all the users need. They do need to access top directly
Also, this free access can cause problems:
If a user is not careful or is malicious, such a direct access to S.top can invalidate the stack operations’ outcome
It also limits the implementer from evolving/modifying the implementation of the data type
Initialization of Variables
In C, initialization of variables is left to the user.
For example, the member “top” of stack S is not initialized. All calls to push() or pop() cause errors
C++ considers initialization too important to leave to the users’ unreliable memory to remember to initialize.
Even if users remember, observe that:
In the definition of stack, it is illegal to write: int top=0;
If top is private, it is illegal to write: stack S; S.top = 0;
And we don’t want to have top public (as we saw)