
上QQ阅读APP看书,第一时间看更新
Chapter 2. Object-Oriented Programming in C++
As C++ is an object-oriented language, it fully supports the object-oriented model. Even though it is possible to write working programs in C++ only by means of the techniques presented in the previous chapter, I strongly suggest that you learn the techniques of this chapter. They are what makes C++ a modern and powerful language. This chapter covers the following topics:
- First, we look into the theoretical foundation of the object-oriented model. It consists of the three cornerstones and the five relations.
- The basic feature of the object-oriented model is the class. A class can be instanced into an object. A class consists of members, which are functions or variables. When located inside a class, they are called methods and fields.
- A class can inherit another class with its members. A method of the baseclass can be virtual, resulting in dynamic binding. This means that the methods connected to an object is bound during the execution of the program rather than its compilation.
- As mentioned in the previous chapter, an array consists of a sequence of values. However, it can also consist of a sequence of objects. In that case, there are some restrictions on the class in order to ensure that all objects are properly initialized.
- Also in the previous chapter, we looked at pointers. A pointer can very well point at an object. The object may hold a pointer of its own that points at another object of the same class. This will result in a linked list, a very useful structure.
- C++ holds a number of operations that operate on values of basic types. We can also extend our classes so that objects of the classes are allowed as operands. It is called operator overloading.
- When an error occurs, an elegant solution is to throw an exception with information about the error to be caught and processed in another part of the program.
- Say that we want a class to hold a list of integers or real values. Do we need to write two different classes? Not at all. Instead, we write a template class. Instead of integer or real, we use a generic type, which we replace with a suitable type when we create an instance of the class.
- In the previous chapter, we organized our code in functions. In this chapter, we organize functions into classes. On top of that, we can place classes and freestanding functions into namespaces.
- Finally, we look into file processing with streams.