- Central to C++ is object-oriented programming (OOP). As just explained, OOP was the impetus for the creation of C++. Because of this, it is useful to understand OOP’s basic principles before you write even a simple C++ program.
- Object-oriented programming took the best ideas of structured programming and combined them with several new concepts.
- Object-oriented programs work the other way around. They are organized around data, with the key principle being “data controlling access to code.”
- In an object-oriented language, you define the data and the routines that are permitted to act on that data. Thus, a data type defines precisely what sort of operations can be applied to that data.
To support the principles of object-oriented programming, all OOP languages, including C++, have three traits in common:
- Inheritance is the process by which one object can acquire the properties of another object.
- This is important because it supports the concept of hierarchical classification.
- Without the use of hierarchies, each object would have to explicitly define all of its characteristics. Using inheritance, an object need only define those qualities that make it unique within its class.
- It can inherit its general attributes from its parent. Thus, it is the inheritance mechanism that makes it possible for one object to be a specific instance of a more general case.
- Polymorphism (from Greek, meaning “many forms”) is the quality that allows one interface to access a general class of actions.
- A simple example of polymorphism is found in the steering wheel of an automobile. The steering wheel (the interface) is the same no matter what type of actual steering mechanism is used.
- That is, the steering wheel works the same whether your car has manual steering, power steering, or rack-and-pinion steering.
- Polymorphism helps reduce complexity by allowing the same interface to specify a general class of action.
- Encapsulation is a programming mechanism that binds together code and the data it manipulates, and that keeps both safe from outside interference and misuse.
- In an object-oriented language, code and data can be bound together in such a way that a self-contained black box is created.
- Within the box are all necessary data and code. When code and data are linked together in this fashion, an object is created. In other words, an object is the device that supports encapsulation.
- C++’s basic unit of encapsulation is the class. A class defines the form of an object. It specifies both the data and the code that will operate on that data.
- C++ uses a class specification to construct objects. Objects are instances of a class. Thus, a class is essentially a set of plans that specifies how to build an object.