Docsity

C++ Inheritance & Polymorphism: Abstract Base, Virtual Functions & Template Classes, Papers of Computer Science

Toggle sidebar
bg1
BASE-CLASS AND DERIVED-CLASS POINTERS
1. An object of a derived class can be treated as an object of its corresponding
public base class. However, the reverse is not true.
2. An explicit cast can be used to convert a base-class pointer to a derived-class
pointer. Such a pointer should not be dereferenced unless it actually points to
an object of the derived class type.
3. A pointer to a derived-class object may be implicitly converted into a pointer
for a base-class object.
4. Example of using a base class pointer:
#include <iostream>
using std::cout;
using std:: endl;
#include <cstring>
class base {
public:
base(char* v) { strcpy(b_info, v); }
char* show() { return b_info; }
private:
char b_info[80];
};
class derived : public base {
public:
derived(char* v, char* b);
char* show() { return d_info; }
private:
char d_info[80];
};
derived::derived(char* v, char* b) : base(b)
{
strcpy(d_info, v);
}
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a

Partial preview of the text

Download C++ Inheritance & Polymorphism: Abstract Base, Virtual Functions & Template Classes and more Papers Computer Science in PDF only on Docsity!

BASE-CLASS AND DERIVED-CLASS POINTERS

  1. An object of a derived class can be treated as an object of its corresponding public base class. However, the reverse is not true.
  2. An explicit cast can be used to convert a base-class pointer to a derived-class pointer. Such a pointer should not be dereferenced unless it actually points to an object of the derived class type.
  3. A pointer to a derived-class object may be implicitly converted into a pointer for a base-class object.
  4. Example of using a base class pointer: #include using std::cout; using std:: endl; #include class base { public: base(char* v) { strcpy(b_info, v); } char* show() { return b_info; } private: char b_info[80]; }; class derived : public base { public: derived(char* v, char* b); char* show() { return d_info; } private: char d_info[80]; }; derived::derived(char* v, char* b) : base(b) { strcpy(d_info, v); }

BASE-CLASS AND DERIVED-CLASS POINTERS (CONTINUED)

int main() { derived x("Derived", "Base"); derived *ptr = &x; base bptr = (base) &x; cout << "Derived Class pointer points to..."; cout << ptr->show() << endl; cout << "Base Class pointer points to..." << bptr->show() << endl; return 0; } Output is: Derived Class pointer points to...Derived Base Class pointer points to...Base

VIRTUAL FUNCTIONS AND POLYMORPHISM

  1. With virtual functions and polymorphism, it becomes possible to design and implement systems that are more easily extensible. a) Programs can be written to generically process, as base-class objects, objects of all existing classes in a hierarchy. b) Programs can be written to process objects of types that may not exist when the program is under development.
  2. Virtual functions and polymorphic programming can eliminate the need for switch logic. a) The programmer can use the virtual function mechanism to perform the equivalent logic automatically, thus avoiding the kinds of errors typically associated with switch logic. b) Client code making decisions about object types and representations indicates poor class design.
  3. Suppose a set of shape classes such as Circle, Triangle, Rectangle, Square, etc. are all derived from base class Shape. a) In OOP, each of these classes might be endowed with the ability to draw itself. i) Although each class has its own draw function, the draw function for each shape is quite different. b) When drawing a shape, whatever that shape might be, it would be nice to be able to treat all these shapes generically as objects of the base class Shape. i) To draw any shape we could simply call function draw of base class Shape and let the program determine dynamically (i.e. at execution time) which derived class draw function to use.

VIRTUAL FUNCTIONS AND POLYMORPHISM (CONTINUED)

c) To enable this kind of behavior: i) We declare draw in the base class shape as a virtual function: virtual void draw() const; ii) We redefine draw in each of the derived classes to draw the appropriate shape. iii) We declare a base-class pointer to point to the derived-class object. circle c; shape *shapePtr = &c;

  1. We invoke the draw function using the pointer; the program will choose the correct derived class's draw function dynamically (i.e. at execution time). This is called dynamic binding. shapePtr->draw();
  2. If a virtual function is called by referencing a specific object by name and using the dot member selection operator, the reference is resolved at compile time (this is called static binding ), and the virtual function that is called is the one defined for (or inherited by) the class of that particular object.
  3. Derived classes can provide their own implementations of a base class virtual function if necessary, but if they do not, the base class's implementation is used.
  4. Rewrite of base-class and derived-class pointer example using a virtual base class: #include using std::cout; using std:: endl; #include <string.h>

ABSTRACT BASE CLASSES AND CONCRETE CLASSES

  1. There are many situations in which it is useful to define classes for which the programmer never intends to instantiate any objects. Such classes are called abstract classes. a) Because these are used only as base classes, we will normally refer to them as abstract base classes. b) No objects of an abstract class may be instantiated in a program.
  2. Classes from which objects can be instantiated are called concrete classes.
  3. A class is made abstract by declaring one or more of its virtual functions to be pure. A pure virtual function is one with an initializer of = 0 in its declaration. virtual float earnings() const = 0; // pure virtual a) Typically, the derived class redefines the base class's pure virtual function.
  4. If a class is derived from a class with a pure virtual function without supplying a definition for that pure virtual function in the derived class, then that virtual function remains pure in the derived class. Consequently, the derived class is also an abstract class (and cannot have any objects).

CASE STUDY: VIRTUAL FUNCTIONS AND POLYMORPHISM

  1. The following case study of virtual functions and polymorphism uses an inheritance structure headed with the abstract base class Shape. a) Shape has a pure virtual function, printShapeName, so Shape is an abstract base class. b) Shape contains two other virtual functions, area and volume, each of which has an implementation that returns a value of zero. c) Point inherits these implementations from Shape. This makes sense because both the area and volume of a point are zero. d) Circle inherits the volume function from Point, but Circle provides its own implementation for the area function. e) Cylinder provides its own implementations for both the area function and the volume function. f) Note that although Shape is an abstract base class, it still contains implementations of certain member functions, and these implementations are inheritable. g) The driver program takes advantage of polymorphism to loop through arrayOfShapes and print the shape name, area, and volume of each object to which the array points using dynamic binding. // SHAPE.H // Definition of abstract base class Shape #ifndef SHAPE_H #define SHAPE_H class Shape { public: virtual float area() const { return 0.0; } virtual float volume() const { return 0.0; } virtual void printShapeName() const = 0; // pure virtual virtual void print() const = 0; // pure virtual }; #endif

CASE STUDY: VIRTUAL FUNCTIONS AND POLYMORPHISM

(CONTINUED)

// POINT1.CPP

// Member function definitions for class Point #include using std::cout; #include "point1.h" Point::Point(int a, int b) { setPoint(a, b); } void Point::setPoint(int a, int b) { x = a; y = b; } void Point::print() const { cout << '[' << x << ", " << y << ']'; } ostream &operator<<(ostream &output, const Point &p) { p.print(); // call print to output the object return output; // enables concatenated calls }

CASE STUDY: VIRTUAL FUNCTIONS AND POLYMORPHISM

(CONTINUED)

// CIRCLE1.H

// Definition of class Circle #ifndef CIRCLE1_H #define CIRCLE1_H #include "point1.h" class Circle : public Point { friend ostream &operator<<(ostream &, const Circle &); public: // default constructor Circle(double r = 0.0, int x = 0, int y = 0); void setRadius(double); double getRadius() const; virtual double area() const; virtual void printShapeName() const { cout << "Circle: "; } virtual void print() const; private: double radius; // radius of Circle }; #endif

CASE STUDY: VIRTUAL FUNCTIONS AND POLYMORPHISM

(CONTINUED)

// CYLINDR1.H

// Definition of class Cylinder #ifndef CYLINDR1_H #define CYLINDR1_H #include "circle1.h" class Cylinder : public Circle { friend ostream &operator<<(ostream &, const Cylinder &); public: // default constructor Cylinder(double h = 0.0, double r = 0.0, int x = 0, int y = 0); void setHeight(double); virtual double area() const; virtual double volume() const; virtual void printShapeName() const { cout << "Cylinder: "; } virtual void print() const; private: double height; // height of Cylinder }; #endif

CASE STUDY: VIRTUAL FUNCTIONS AND POLYMORPHISM

(CONTINUED)

// CYLINDR1.CPP

// Member and friend function definitions for class Cylinder #include using std::cout; #include "cylindr1.h" Cylinder::Cylinder(double h, double r, int x, int y) : Circle(r, x, y) // call base-class constructor { setHeight(h); } void Cylinder::setHeight(double h) { height = h > 0? h : 0; } double Cylinder::area() const { // surface area of Cylinder return 2 * Circle::area() + 2 * 3.14159 * getRadius() * height; } double Cylinder::volume() const { return Circle::area() * height; } void Cylinder::print() const { Circle::print(); cout << "; Height = " << height; } ostream &operator<<(ostream &output, const Cylinder& c) { c.print(); // call print to output the object return output; // enables concatenated calls }

CASE STUDY: VIRTUAL FUNCTIONS AND POLYMORPHISM

(CONTINUED)

// Loop through arrayOfShapes and print the shape name, // area, and volume of each object to which the array points // using dynamic binding. cout << setiosflags(ios::showpoint) << setprecision(2); for (int i = 0; i < 3; i++) { arrayOfShapes[i]->printShapeName(); cout << endl; arrayOfShapes[i]->print(); cout << "\nArea = " << arrayOfShapes[i]->area() << "\nVolume = " << arrayOfShapes[i]->volume() << endl << endl; } return 0; } Output is: Point: [7, 11] Circle: [22, 8]; Radius = 3. Cylinder: [10.00, 10.00]; Radius = 3.3; Height = 10. Point: [7.00, 11.00] Area = 0. Volume = 0. Circle: [22.00, 8.00]; Radius=3. Area = 38. Volume = 0. Cylinder: [10.00, 10.00]; Radius=3.3; Height=10. Area = 275. Volume = 342.

COUT AND POLYMORPHISM

  1. In the prior Shape example, the statement in main(): arrayOfShapes[i]->print(); can be replaced with: cout << *arrayOfShapes[i];
  2. The following function needs to be coded in the file shape.cpp and declared as a friend function in the Shape class: #include "shape.h" ostream& operator<<(ostream& output, const Shape& s) { s.print(output); return output; }
  3. Change the function prototype of print in the Shape class to: virtual ostream& print(ostream&) const = 0;
  4. Change the print functions in the derived classes to reflect ostream& argument and ostream& return type.

NEW CLASSES AND DYNAMIC BINDING

  1. New kinds of classes are regularly added to systems. a) New classes are accommodated by dynamic binding (also called late binding). i) The type of an object need not be known at compile time for a virtual function call to be compiled. ii) At execution time, the virtual function call is matched with the member function of the receiving object.
  2. Dynamic binding enables independent software vendors (ISVs) to distribute software without revealing proprietary secrets. a) Software distributions can consist of only header files and object files. No source code needs to be revealed. b) Software developers can then use inheritance to derive new classes from those provided by the ISVs. c) The software that works with the classes the ISVs provide will continue to work with the derived classes and will use (via the dynamic binding) the redefined virtual functions provided in these classes.
  3. Dynamic binding requires that at execution time, the call to a virtual member function be routed to the virtual function version appropriate for the class. a) A virtual function table called the vtable (or vtab) is implemented as an array containing function pointers. b) Each class that contains virtual functions has a vtable. i) For each virtual function in the class, the vtable has an entry containing a function pointer to the version of the virtual function to use for an object of that class. ii) The virtual function to use for a particular class could be the function defined in that class, or it could be a function inherited either directly or indirectly from a base class higher in the hierarchy.
  4. When a base class provides a virtual member function, derived classes can redefine the virtual function, but they do not have to redefine it. a) Thus a derived class can use a base class's version of a virtual member function, and this would be indicated in the vtable.

NEW CLASSES AND DYNAMIC BINDING (CONTINUED)

  1. Each object of a class with virtual functions contains a pointer to the vtable for that class. a) This pointer is not accessible to the programmer. b) The appropriate function pointer in the vtable is obtained and dereferenced to complete the call at execution time. c) This vtable lookup and pointer dereferencing require nominal execution time overhead, usually less than the best possible client code.