Introduction to Object-Oriented Programming (OOP)
Total Page:16
File Type:pdf, Size:1020Kb
QUIZ Write the following for the class Bar: • Default constructor • Constructor • Copy-constructor • Overloaded assignment oper. • Is a destructor needed? Or Foo(x), depending on how we want the initialization to be made. Criticize! Ch. 15: Polymorphism & Virtual Functions Virtual functions enhance the concept of type. There is no analog to the virtual function in a traditional procedural language. As a procedural programmer, you have no referent with which to think about virtual functions, as you do with almost every text other feature in the language. Features in a procedural language can be understood on an algorithmic level, but, in an OOL, virtual functions can be understood only from a design viewpoint. Remember upcasting Draw the UML diagram! We would like the more specific version of play() to be called, since flute is a Wind object, not a generic Instrument. Ch. 1: Introduction to Objects Remember from ch.1 … Early binding vs. late binding “The C++ compiler inserts a special bit of code in lieu of the absolute call. This code calculates the text address of the function body, using information stored in the object at runtime!” Ch. 15: Polymorphism & Virtual Functions virtual functions To cause late binding to occur for a particular function, C++ requires that you use the virtual keyword when declaring the function in the base text class. All derived-class functions that match the signature of the base-class declaration will be called using the virtual mechanism. example It is legal to also use the virtual keyword in the derived-class declarations, but it is redundant and can be confusing. Extensibility “With play( ) defined as virtual in the base class, you can add as many new types as you want without changing the tune( ) function. In a well-designed OOP program, most or all of your text functions will follow the model of tune( ) and communicate only with the base-class interface. Such a program is extensible because […] the functions that manipulate the base-class interface will not need to be changed at all to accommodate the new classes.” Read and understand the full program C15:Instrument4.cpp How C++ implements late binding The typical compiler creates a single table (called the VTABLE) for each class that contains virtual functions. The compiler places the addresses of the virtual text functions for that particular class in the VTABLE. In each class with virtual functions, it secretly places a pointer, called the vpointer (abbreviated as VPTR), which points to the VTABLE for that object. If function is not overridden in the base class, the address of its base-class version is placed in the VTABLE. Here’s what a call to adjust( ) for a Brass object looks like, if made through an Instrument pointer: (An Instrument reference produces the same result) The memory overhead is only one pointer, no matter how many virtual functions there are! Installing the vpointer This is where the default constructor is essential: In the Instrument examples, the compiler creates a default constructor that does nothing except initialize VPTR. This constructor, of course, is automatically called for all Instrument objects before you can do anything with them, so you know that it’s always safe to call virtual functions. Objects are different early binding ? and references ? “[…] upcasting deals only with addresses ” (?) Means: Upcasting is not necessarily implemented by the compiler via late binding. • Actually, if given the choice, the compiler will probably prefer early binding, since it results in faster code. But when the compiler does not “have” the object (i.e. when the object is passed by pointer or reference), it must use late binding. Code example Abstract base classes and pure virtual functions Often in a design, you want the base class to present only an interface for its derived classes. That is, you don’t want anyone to actually create an object of the base class, only to upcast to it so that its interface can be used. We say that the virtual function is pure. A class with only These functions exist pure virtual only to create a common interface for functions is all the derived classes. called a pure abstract class. Code example The compiler still reserves a slot for a pure virtual function in the VTABLE, but does not to put an address in that particular slot. QUIZ Write a pure virtual function foo in the parent class, and redefine it as a virtual function in the child class. QUIZ In practical terms, what is the difference between a virtual function and a pure virtual one? Solution In practical terms, what is the difference between a virtual function and a pure virtual one? A: If a class has a pure virtual function, no objects of that class can be instantiated. QUIZ Does this code compile? (Assume that Abstract::bar and Derived::foo are defined in another file.) int main(){ Derived d; } Source: http://stackoverflow.com/questions/8931612/do-all-virtual-functions-need-to-be-implemented-in-derived-classes Solution Yes. A derived class does not need to override virtual functions from the parent, only pure virtual ones! int main(){ Derived d; } Actually, not every derived class needs to override the pure virtuals from the parent! A function can stay pure virtual in several levels of the hierarchy. (But, eventually, all pure virtuals must be overriden in order to be able to instantiate int main(){ DerivedMore dm; objects.) } Virtual functions in multi-level hierarchies Individual work for next time: • Read and understand the section – Under the hood – Why virtual functions? • End-of-chapter exercise 1 EOL 1 QUIZ How is the late binding of virtual functions implemented in the C++ compiler? How C++ implements late binding The typical compiler creates a single table (called the VTABLE) for each class that contains virtual functions. The compiler places the addresses of the virtual text functions for that particular class in the VTABLE. In each class with virtual functions, it secretly places a pointer, called the vpointer (abbreviated as VPTR), which points to the VTABLE for that object. QUIZ Why do we need virtual functions? virtual functions To cause late binding and upcasting to occur for a particular function, C++ requires that you use the virtual keyword when declaring the function in the text base class. All derived-class functions that match the signature of the base-class declaration will be called using the virtual mechanism. QUIZ Why do we need pure virtual functions? Abstract base classes and pure virtual functions Often in a design, you want the base class to present only an interface for its derived classes. That is, you don’t want anyone to actually create an object of the base class, only to upcast to it so that its interface can be used. We say that the virtual function is pure. Common misconception: It’s illegal to provide a definition for a pure virtual function But, wait a second: If we cannot instantiate objects of type Abstract, what use can the definition be? It is legal to provide a definition for a pure virtual function! We can always access the parent function using the scope resolution operator! … however, the pure virtual function definition cannot be inline: QUIZ: Show how to access the Pet pure virtual code in main Inheritance and the VTABLE It is also possible to add new virtual functions to the derived class. example VTABLEs created by the compiler for Pet and Dog: VTABLEs created by the compiler for Pet and Dog: Problem: We cannot use sit() with an upcast pointer or reference! This is the opposite of upcasting – It is called downcasting. Solution: typecast manually! Extra-credit quiz Ch. 3: The C in C++ C++ explicit casts Back to Ch.15 Run-time type identification (RTTI) RTTI is all about casting base-class pointers down to derived-class pointers (“up” and “down” are relative to a typical class diagram, with the base class at the top). • Casting up happens automatically, with no coercion, because it’s completely safe. • Casting down is unsafe because there’s no compile time information about the actual types, so you must know exactly what type the object is. If you cast it into the wrong type, you’ll be in trouble. Run-time type identification (RTTI) dynamic_cast does its work at runtime, using the virtual table • It tends to be more expensive than the other C++-style casts. QUIZ Is this use of the function sit( ) correct? Explain. Solution Is this use of the function sit() correct? Explain. Yes. Remember that, when the compiler “has” the actual object, it uses early binding, so the VTABLE never comes into play. Polymorphism - definition It is the virtual function mechanism described in this chapter, involving the VTABLE, VPTRs, upcasting, downcasting and RTTI. It allows late binding to occur. Object slicing or Why we should not use pass-by- value with polymorphism Do you remember how parameters are passed to a function? An object the size of Pet is pushed on the stack (and cleaned up after the call) Fluffy is sliced Do. Not. Slice. Fluffy. Object slicing actually removes part of the object as it copies it into the new object (rather than simply changing the meaning of an address, as when using a pointer or reference). Because of this, upcasting into an object is not done often; in fact, it’s usually something to watch out for and prevent. Overloading & overriding In Chapter 14, we learned that redefining an overloaded function in the base class hides all of the other base-class versions of that function. When virtual functions are involved the behavior is a little different.