Object-Oriented Programmingvoid printIterativeRev(Node* list) { // if the list is empty, just return if (!list) return; // point to the first node Node* head = list; // get length of the list int length = 0; while (head) { head = head->next; length++; } // for each node in the list for (int i = length; i > 0; i--) { Node* previousPtr; // start to first node Node* currentPtr = list; // go to node at position 'i' int position = 0; while (position < i) { // save pointer to previous node previousPtr = currentPtr; currentPtr = currentPtr->next; position++; } // print previous data cout << previousPtr->data << endl; } }
Other OO languages use different terminology than C++. Here are some equivalents:
OOP | C++ |
Object | Class object or instance |
Instance variable | Private data member |
Method | Public member function |
Message passing | Calling a public member function |
Within a class, all of the data and functions are related. Within a program, classes can be related in various ways.
Relation by composition is called a has-a relationship.
A car has a motor.
Inheritance Example
class Time { public: void Set(int h, int m, int s); void Write(void) const; void Increment(void); Time (int h, int m, int s); Time(void); private: int hrs; int mins; int secs; };
enum ZoneType {EST, CST, MST, PST, EDT, CDT, MDT, PDT}; class ExtTime : public Time { public: void Set(int h, int m, int s, ZoneType z); void Write(void) const; ExtTime(int h, int m, int s, ZoneType z); ExtTime(void); private: ZoneType zone; };