CSE 374, Lecture 22: C++ Classes
Object-Oriented Programming
We've now seen OO-programming (Java) and procedural programming (C). As a refresher, what distinguishes object-oriented design, and why might you use it?
- Polymorphism. In essence, polymorphism is the ability access different objects through the same interface. For instance, if you have an interface that represents an electronic device, that interface would have the ability to turn the device on and off. You can use the actual physical types - computer, phone, television, etc - as if they were an electronic device, because they all have the on/off capability.
- Inheritance. This is one of the meatiest pieces of OO programming. Inheritance allows the sharing of BEHAVIORS. For instance, a Square is a type of Rectangle, and has the same way to compute its area (width times height) - therefore by make Square inherit from Rectangle, we can share that behavior and avoid duplicating the code.
- Encapsulation. We group data and behavior together to form logical units. For instance, we can have a linked list class that represents the data stored in the list but also all the operations that you can perform on the list, disallowing any operations that we don't want to support.
Example
In class we developed a String class (see example files). Some key concepts we examined:
- Class declaration is in the header file, including fields of the class as well as member functions. Implementations of the member functions are in the .cpp file.
- public, protected, and private have slightly different syntax in C++ than in Java.
- Constructors: in C++ there are four types of constructors.
- The destructor is a special function that is used to clean up the object when you are finished with it - for example, freeing any data that has been allocated on the heap (the raw_ string in this case). The destructor is declared as taking no arguments and prefixed with a tilde:
~String();
You will NEVER call the destructor function directly - the compiler will do it for you automatically whenever (1) the object goes out of scope if it was allocated on the heap or (2) the object is deleted via the "delete" keyword (ie "delete s;"). Your destructors should always be declared as "virtual" (ie "virtual ~String()'") - we will talk about why in a future lecture.
- It would be great if we could use our String object with << to cout! We can do that by overloading the << operator for our class. See the file for an example of how to do that.k