Learning Objectives

advertisement

Learning Objectives

• Relationships Among Objects in an Inheritance

Hierarchy.

• Invoking Base-class Functions from Derived Class

Objects.

• Aiming Derived-Class Pointers at Base Class Objects.

• Derived-Class Member-Function calls via Base-Class

Pointers.

• Virtual Functions.

• Abstract classes and pure virtual functions.

polymorphism

• The word Polymorphism means many forms.

• In programming this word is meant to reuse the single code multiple times.

• Its obvious that when we do inheritance between two classes, all the methods and properties of the first class are derived to the other class so that this becomes the child class which adobes all the functionality of base class. It can also possesses its own separate methods.

• But there is a big problem in inheriting the second class to the first class as it adobes all the methods same as the base class has, which means that after inheritance both(base class& child class) have the methods of same name

Con..

• Example:

• ___Base Class___

• public class fish

{ public void eat()

{ console.writeline("fish eat");

} public void swim()

{ console.writeline("fish swim");

}

}

Cont…

• __Derived Class______

{ class Dolphen:fish

} public void eat()

{ console.writeline("fish eat");

} public void swim()

{ console.writeline("fish swim");

}

Cont…

• when we Inherit two classes, all the methods with the same name and same body are aboded by the derived class .Both methods have the same name but if we change the body of the second method then it makes

Compiler disturb whether to compile base class method or derived class's method first...

• each of the child classes has a separate implementation for the function area(). This is how

polymorphism is generally used. You have different classes with a function of the same name, and even the same parameters, but with different implementations.

Cont…

• ____Base Class___

{ public class fish public void eat()

{ console.writeline("fish eat");

} public void swim()

{ console.writeline("fish swim");

}

}

Cont…

• ______Derived Class______

{ class Dolphin:fish

} public void eat()

{ console.writeline("Dolphin can eat");

} public void swim()

{ console.writeline("Dolphin can swim");

}

In this example we have changed the body of the methods of Derived class.Now

this will make the Compiler disturb to compile which method first, because they both have same name but different bodies.

Cont…

• Polymorphism is used in changing the name of the methods of both base & derived class. Infect is done by adding the "virtual" keyword before the base class method, and the "override" keyword before the derived class method. As shown in this exmple:

____Base Class___

{ public class fish

{ public virtual void eat()

Console.WriteLine("fish eat");

{

} public virtual void swim()

Console.WriteLine("fish swim");

}

}

Cont…

• ______Derived Class______ class Dolphin : fish

{

}

}

{ public override void eat()

Console.WriteLine("Dolphin can eat");

{

} public override void swim()

Console.WriteLine("Dolphin can swim");

• This is actually the Polymorphism in which virtual keyword with the base class method and override keyword with the derived class method. It helps the compiler to select the method to be executed.

• class Program

{

{ public class fish public virtual void eat()

{ } public virtual void swim()

{ } public virtual void dive()

{}

} public class Dolphin : fish

Cont..

}

Cont..

• {

} public override void eat()

{ Console.WriteLine("Dolphin eats Plants"); } public override void swim()

{ Console.WriteLine("Dolphin swims quickly"); } public override void dive()

{ Console.WriteLine("Dolphin dive deeply "); } public void dance()

{ Console.WriteLine("Dolphin can Dance"); }

Cont..

• public class Shark : fish

{ public override void eat()

{ Console.WriteLine("Shark eats dead animal"); } public override void swim()

{ Console.WriteLine("Sharks swim fastest than Dolphin"); } public override void dive()

{ Console.WriteLine("Sharks Dive deeper than Dolphin"); } public void kill()

{ Console.WriteLine("Shark kills Others"); }

}

Cont..

• static void Main(string[] args)

{

Dolphin D = new Dolphin();

D.dance();

D.dive();

D.eat();

D.swim();

Shark S = new Shark();

S.kill();

S.dive();

S.eat();

S.swim();

Console.ReadLine();

}

Cont…

• Polymorphism

– Associating many meanings to one function

– Virtual functions provide this capability

– Fundamental principle of object-oriented programming!

• Virtual - Existing in "essence" though not in fact

• Virtual Function

• Can be "used" before it’s "defined“

When base class has a common function whose meaning depends on the actual derived class, we want to use before defining them

– Must assign multiple meanings to the same function ( polymorphism )

– Powerful

Tells compiler:

– "Don’t know how function is implemented"

– "Wait until used in program"

– "Then get implementation from object instance"

Called late binding or dynamic binding - Virtual functions implement late binding

• Define a method as virtual, and the subclass method overrides the base class method

• E.g., class Shape { public: virtual void Rotate(); virtual void Draw();

…}

Overriding:

• Virtual function definition changed in a derived class

– We say it’s been "overidden"

• Similar to redefined

– Recall: for standard functions

• So: - Virtual functions changed: overridden

- Non-virtual functions changed: redefined

Virtual Functions: Why Not All?

• Clear advantages to virtual functions as we’ve seen

• One major disadvantage: overhead!

– Uses more storage

– Late binding is "on the fly", so programs run slower

• So if virtual functions not needed, should not be used

• If a method is declared virtual in a class,

– … it is automatically virtual in all derived classes

• It is a really, really good idea to make destructors virtual!

virtual ~Shape();

– Reason: to invoke the correct destructor, no matter how object is accessed

Abstract and Concrete Classes

• Abstract Classes

– Classes from which it is never intended to instantiate any objects

• Incomplete—derived classes must define the “missing pieces”.

• Too generic to define real objects.

– Normally used as base classes and called abstract base classes

• Provide appropriate base class frameworks from which other classes can inherit.

• Concrete Classes

– Classes used to instantiate objects

– Must provide implementation for every member function they define

Abstract Base Classes

• Pure virtual functions require no definition

– Forces all derived classes to define "their own" version

• Class with one or more pure virtual functions is: abstract base class

– Can only be used as base class

– No objects can ever be created from it

• Since it doesn’t have complete "definitions" of all it’s members!

• If derived class fails to define all pure’s: It’s an abstract base class too

Abstract Classes and Pure virtual Functions

• Abstract base class can be used to declare pointers and references referring to objects of any derived concrete class

• Pointers and references used to manipulate derived-class objects polymorphically

• Polymorphism is particularly effective for implementing layered software systems – e.g.,

1. Reading or writing data from and to devices.

2. Iterator classes to traverse all the objects in a container.

Example – Graphical User Interfaces

• All objects on the screen are represented by derived classes from an abstract base class

• Common windowing functions

• Redraw or refresh

• Highlight

• Respond to mouse entry, mouse clicks, user actions, etc.

• Every object has its own implementation of these functions

• Invoked polymorphically by windowing system

#include <iostream> using namespace std; class Polygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } virtual int area (void) =0;

}; class Rectangle: public Polygon { public: int area (void) { return (width * height); }

}; class Triangle: public Polygon { public: int area (void) { return (width * height / 2); }

}; int main () {

Rectangle rect;

Triangle trgl;

Polygon * ppoly1 = &rect;

Polygon * ppoly2 = &trgl; ppoly1->set_values (4,5); ppoly2->set_values (4,5); cout << ppoly1->area() << '\n'; cout << ppoly2->area() << '\n'; return 0; }

OUTPUT:

20

10

Pure Virtual Functions

• A class is made abstract by declaring one or more of its virtual functions to be “pure” - i.e., by placing "= 0" in its declaration

• Base class might not have "meaningful” definition for some of its members!

– Its purpose solely for others to derive from

• Recall class Figure

– All figures are objects of derived classes

• Rectangles, circles, triangles, etc.

– Class Figure has no idea how to draw!

• Make it a pure virtual function: virtual void draw() = 0;

– "= 0" is known as a pure specifier .

– Tells compiler that there is no implementation.

• Don’t need to know how to use it! - Principle of information hiding

• Virtual function table

– Compiler creates it

– Has pointers for each virtual member function

– Points to location of correct code for that function

• Objects of such classes also have pointer

– Points to virtual function table

Pure virtual Functions (continued)

• Every concrete derived class must override all base-class pure virtual functions

– with concrete implementations

• If even one pure virtual function is not overridden, the derived-class will also be abstract

– Compiler will refuse to create any objects of the class

– Cannot call a constructor

Purpose:

• When it does not make sense for base class to have an implementation of a function

• Software design requires all concrete derived classes to implement the function by Themselves

Why Do we Want to do This?

• To define a common public interface for the various classes in a class hierarchy

– Create framework for abstractions defined in our software system

• The heart of object-oriented programming

• Simplifies a lot of big software systems

• Enables code re-use in a major way

• Readable, maintainable, adaptable code

Relationships among objects in an inheritance hierarchy

• In public inheritance an object of a derived class can be treated as an object of its base class.

• Each derived class object is an object of its base class

• The is-a relationship applies only from a derived class to its direct and indirect base classes.

Invoking base-class functions from derived-class objects

• Three ways to aim base and derived class pointers at base and derived class objects.

• 1.Base class pointer at a base class object and invoke base class functionality

• 2.derived class pointer at a derived class object and invoke derived class functionality.

• Then we demonstrate the relationship between derived classes and base classes

• 3. base class pointer at a derived class object and showing that the base class functionality is indeed available in the derived class object

Cont…

• The relationship between derived classes and base classes (is-a relationship of inheritance ) by aiming a base class pointer at a derived class object and showing that the base class functionality is indeed available in the derived

–class object.

• Creating objects and displaying their contents

• Aiming a base-class pointer at a base class object

• Aiming a derived class pointer at a derived class object

• Aiming a base class pointer at a derived class object

Aiming derived class pointers at base class objects

• Assign the address of a derived class object to a base class pointer because a derived class object is a base class object.

• The object points the pointer (ie. The base class object)

• The object does not provide a member function nor does it provide a data member to set

• I f the memory does not belong to the object , the member function might overwrite other important data in memory, possible data that belongs to a different object.

Cont…

• Example:

• If B is a base class and D is a derived class from b, then a pointer declared as a pointer to B can also be a pointer to

D.

• B *cptr; //pointer to class B type variable

• B b; //base object

• D d; //derived object

• Cptr =&b; //cptr points to object b

• We can make cptr to point to the object d as follows:

Cptr = &d; //cptr points to object d

• This is perfectly valid with C++ because d is an object derived from the class B.

Derived –class member –function call via base class pointers

• Derived class only members from a base class pointer that aimed at a derived class object if we explicitly cast the base class pointer to a derived class pointer – this is known as downcasting.

• Its possible to aim a base class pointer at a derived class object.

• A base class pointer can be used to invoke only the functions declared in the base class.

Virtual functions

• Virtual Function:

• A virtual function is a function in a base class that is declared using the keyword virtual. Defining in a base class a virtual function, with another version in a derived class, signals to the compiler that we don't want static linkage for this function.

• selection of the function to be called at any given point in the program to be based on the kind of object for which it is called. This sort of operation is referred to as dynamic linkage, or late binding.

• Pure Virtual Functions:

• It's possible to include a virtual function in a base class so that it may be redefined in a derived class to suit the objects of that class

Virtual functions

• Shape classes such as circle , triangle , rectangle and square are all derived from base class shape.

• Each of these classes might be endowed with the ability to draw itself via a member function draw, but the function for each shape is quite different.

In a program that draws a set of shapes, it would be useful to be able to treat all the shapes generally as objects of the base class shape.

• Then, to draw any shape, we could simply use a base-class shape pointer to invoke function draw

Abstract classes

• The class as a type assume that programs will create objects of that type.

• To define classes from which the programmer never intends to instantiate any objects ,such classes are called abstract classes.

• Normally these classes are used as base classes in inheritance hierarchies which is referred as abstract base classes.

• These classes cannot be used to instantiate objects, because the abstract classes are incomplete in which the derived classes must define the “missing pieces.”

Cont..

• The purpose of an abstract class is to provide an appropriate base class from which other classes can inherit.

• Classes that can be used to instantiate objects are called concrete classes.

• Such classes provide implementations of every member function they define.

• The abstract class is to provide and appropriate base class from which other classes can inherit.

Cont…

• Classes that can be used to instantiate objects are called concrete classes.

• Such classes proved implementations of every member function they define.

• Example:1. abstract base class- two dimensional shape

• derive concrete classes- square, circle and triangle.

Cont…

• Example-2:

• Abstract base class: three dimensional shape

• Derive such classes: cube, sphere and cylinder.

• If someone tells you to “draw the twodimensional shape,” what shape would you draw?

• Concrete classes provide the specifies that make it reasonable to instantiate objects.

Pure virtual function

• A class is made abstract by declaring one or more of its virtual functions to be “pure” A pure virtual function is specified by placing

“=0” in its declaration, as in

• virtual void draw() const = 0; //pure virtual function

• The “=0” is known as a pure specifier .

Cont…

• Pure virtual functions do not provide implementations.

• Every concrete derived class must override all base-class pure virtual functions with concrete implementations of those functions.

• The difference between a virtual function and a pure virtual function is that a virtual function has an implementation and gives the derived class the option of overriding the function

Cont…

• A pure virtual function does not provide an implementation and requires the derived class to override the function (for that derived class to be concrete; otherwise the derived class remains abstract)

• Example:

• A company pays its employees weekly.

Cont…

• Types of four:

• 1. salaried employees are paid a fixed weekly regardless of the number of hours worked

2. Hourly employees are paid by the hour and receive overtime pay for all hours worked in excess of 40 hours

3. Commission employees are paid a percentage of their sales and base-salary-plus-commission employees receive a base salary plus a percentage of their sales.

4. For the current pay period, the company has decided to reward base-salary-plus-commission employees by adding 10 percent to their base salaries.

Write a c++ program that performs its payroll calculations polymorphically.

• example:

Cont… employee

S alaried employee

Commission employee

Basepluscommission employee

Hourly employee

#include <iostream> using namespace std; class Polygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } virtual int area (void) =0;

}; class Rectangle: public Polygon { public: int area (void) { return (width * height); }

}; class Triangle: public Polygon { public: int area (void) { return (width * height / 2); }

}; int main () {

Rectangle rect;

Triangle trgl;

Polygon * ppoly1 = &rect;

Polygon * ppoly2 = &trgl; ppoly1->set_values (4,5); ppoly2->set_values (4,5); cout << ppoly1->area() << '\n'; cout << ppoly2->area() << '\n'; return 0; }

OUTPUT:

20

10

this Pointer:

Special pointer this is used to access the pure virtual members of abstract base class.

Example: In abstract base class Polygon the special pointer this is used to access the pure virtual members, even though Polygon itself has no implementation for this function:

#include <iostream> // pure virtual members can be called // from the abstract base class using namespace std; class Polygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } virtual int area() =0; void printarea() { cout << this->area() << '\n'; } }; class Rectangle: public Polygon { public: int area (void) { return (width * height); } }; class Triangle: public Polygon { public: int area (void) { return (width * height / 2); } }; int main () {

Rectangle rect;

Triangle trgl;

Polygon * ppoly1 = &rect;

Polygon * ppoly2 = &trgl; ppoly1->set_values (4,5); ppoly2->set_values (4,5); ppoly1->printarea(); ppoly2->printarea(); return 0; }

OUTPUT:

20

10

Download