Object-oriented programming is a design philosophy; it is a set of rules and patterns used to achieve robustness and modularity in a program. Acquiring the knowledge and experience needed to use these rules properly takes time and may seem a bit complicated. That’s why, in this second introductory article, we will define and explain some of the basic terminology of OOP and give real-life examples to make things easier to understand. With our next article, we’ll introduce the actual C++ syntax.
In our first article, we gave a brief explanation of an object. Basically, an object can be considered a “thing” which performs certain activities. These activities define the object’s behavior. For example, a car is an object, a vehicle. Last time we said that an object consists of data – in the form of fields or properties, and code – in the form of methods. So, for this particular object, one of the possible ways to model it with OOP would be with fields like “model name,” “maximum speed,” “type of engine,” and with methods like “start.”
Although there are many different cars, they all share the same basic features: they have engines, they can be started, etc. It would be inconvenient to write these fields and methods for every single car object you’d want to use in your program. That’s why we define classes. A class is simply a representation of a type of object. It is the blueprint that describes the details of an object, and from that blueprint, individual objects are created. In OOP terms, you would say that “an object is an instance of a class.” This means that when defining your class, you only need to write its features once.
Classes also contain a special method called constructor. This method has the same name as the class, and it is called to create a new object of the class. In a way, it “prepares” the new object. Constructors don’t necessarily have to be written by the programmer (in this case an automatically generated, default constructor is used which simply creates the object), but they can also accept arguments which are then used to not only create the object, but to also set the appropriate fields.
At this point, it’s important to mention that all of this is a part of a process called encapsulation – including all of the resources needed for an object to function properly in one meaningful entity. This is achieved by creating classes.
This is one of the main issues in OOP (and one of the most important steps in building a good object-oriented system). To correctly identify classes, developers use a set of five principles referred to as SOLID principles. These will be discussed later.
Stay tuned for our next article where we’ll explain how classes and objects are constructed in C++!