




Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





Introduction to C++ January 19, 2011 Massachusetts Institute of Technology
Weāve already seen how to define composite datatypes using classes. Now weāll take a step back and consider the programming philosophy underlying classes, known as object-oriented programming (OOP).
Classic āproceduralā programming languages before C++ (such as C) often focused on the question āWhat should the program do next?ā The way you structure a program in these languages is:
With large amounts of data and/or large numbers of tasks, this makes for complex and unmaintainable programs.
Consider the task of modeling the operation of a car. Such a program would have lots of separate variables storing information on various car parts, and thereād be no way to group together all the code that relates to, say, the wheels. Itās hard to keep all these variables and the connections between all the functions in mind.
To manage this complexity, itās nicer to package up self-sufficient, modular pieces of code. People think of the world in terms of interacting objects: weād talk about interactions between the steering wheel, the pedals, the wheels, etc. OOP allows programmers to pack away details into neat, self-contained boxes (objects) so that they can think of the objects more abstractly and focus on the interactions between them.
There are lots of definitions for OOP, but 3 primary features of it are:
Letās see how each of these plays out in C++.
Encapsulation just refers to packaging related stuff together. Weāve already seen how to package up data and the operations it supports in C++: with classes.
If someone hands us a class, we do not need to know how it actually works to use it; all we need to know about is its public methods/data ā its interface. This is often compared to operating a car: when you drive, you donāt care how the steering wheel makes the wheels turn; you just care that the interface the car presents (the steering wheel) allows you to accomplish your goal. If you remember the analogy from Lecture 6 about objects being boxes with buttons you can push, you can also think of the interface of a class as the set of buttons each instance of that class makes available. Interfaces abstract away the details of how all the operations are actually performed, allowing the programmer to focus on how objects will use each otherās interfaces ā how they interact.
This is why C++ makes you specify public and private access specifiers: by default, it assumes that the things you define in a class are internal details which someone using your code should not have to worry about. The practice of hiding away these details from client code is called ādata hiding,ā or making your class a āblack box.ā
One way to think about what happens in an object-oriented program is that we define what objects exist and what each one knows, and then the objects send messages to each other (by calling each otherās methods) to exchange information and tell each other what to do.
Inheritance allows us to define hierarchies of related classes. Imagine weāre writing an inventory program for vehicles, including cars and trucks. We could write one class for representing cars and an unrelated one for representing trucks, but weād have to duplicate the functionality that all vehicles have in common. Instead, C++ allows us to specify the common code in a Vehicle class, and then specify that the Car and Truck classes share this code.
The Vehicle class will be much the same as what weāve seen before:
1 2 3 4
class Vehicle { protected : string license ; int year ;
Similarly, we could make a Truck class that inherits from Vehicle and shares its code. This would give a class hierarchy like the following:
Vehicle
Truck C a r
Class hierarchies are generally drawn with arrows pointing from derived classes to base classes.
There are two ways we could describe some class A as depending on some other class B:
We might want to generate the description for Cars in a different way from generic Vehicles. To accomplish this, we can simply redefine the getDesc method in Car, as below. Then, when we call getDesc on a Car object, it will use the redefined function. Redefining in this manner is called overriding the function.
1 2 3
class Car : public string style ;
Vehicle { // Makes Car inherit from Vehicle
4 public : 5 Car ( const string & myLicense , const int myYear , const string & myStyle ) 6 : Vehicle ( myLicense , myYear ) , style ( myStyle ) {} 7 const string getDesc () // Overriding this member function 8 { return stringify ( year ) + ā ā + style + " : " + license ;} 9 const string & getStyle () { return style ;} 10 };
3.2.1 Programming by Difference
In defining derived classes, we only need to specify whatās different about them from their base classes. This powerful technique is called programming by difference.
Inheritance allows only overriding methods and adding new members and methods. We cannot remove functionality that was present in the base class.
If weād declared year and license as private in Vehicle, we wouldnāt be able to access them even from a derived class like Car. To allow derived classes but not outside code to access data members and member functions, we must declare them as protected.
The public keyword used in specifying a base class (e.g., class Car : public Vehicle {...}) gives a limit for the visibility of the inherited methods in the derived class. Normally you should just use public here, which means that inherited methods declared as public are still public in the derived class. Specifying protected would make inherited methods, even those declared public, have at most protected visibility. For a full table of the effects of different inheritance access specifiers, see http://en.wikibooks.org/wiki/C++ Programming/Classes/Inheritance.
Polymorphism means āmany shapes.ā It refers to the ability of one object to have many types. If we have a function that expects a Vehicle object, we can safely pass it a Car object, because every Car is also a Vehicle. Likewise for references and pointers: anywhere you can use a Vehicle *, you can use a Car *.
We can omit the definition of getDesc from Vehicle by making the function pure virtual via the following odd syntax:
1 class Vehicle { 2 ... 3 virtual const string getDesc () = 0; // Pure virtual 4 };
The = 0 indicates that no definition will be given. This implies that one can no longer create an instance of Vehicle; one can only create instances of Cars, Trucks, and other derived classes which do implement the getDesc method. Vehicle is then an abstract class ā one which defines only an interface, but doesnāt actually implement it, and therefore cannot be instantiated.
Unlike many object-oriented languages, C++ allows a class to have multiple base classes:
1 class Car : public Vehicle , public InsuredItem { 2 ... 3 };
This specifies that Car should have all the members of both the Vehicle and the InsuredItem classes.
Multiple inheritance is tricky and potentially dangerous:
MIT OpenCourseWare http://ocw.mit.edu
6.096 Introduction to C++
January (IAP) 2011
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.