NU-Lec 11_Virtual Functions and Polymorphism - II
NU-Lec 11_Virtual Functions and Polymorphism - II
Lecture No. 11
Virtual Functions and Polymorphism
Notes on virtual
• If a method is declared virtual in a class,
– … it is automatically virtual in all derived classes
class Shape {
public:
virtual void Rotate();
virtual void Draw();
...
}
class Line: public Shape {
public:
void Rotate();
//Use base class Draw method
...
}
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.
• Concrete Classes
– Classes used to instantiate objects
– Must provide implementation for every member function they
define
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
• Example
virtual void draw() const = 0;
8
Pure virtual Functions (continued)
• Every concrete derived class must override all
base-class pure virtual functions
– with concrete implementations
Reading References
Polymorphism:
• http://www.cplusplus.com/doc/tutorial/polymorphism/
• http://www.cs.bu.edu/teaching/cpp/polymorphism/intro/
Virtual Functions
• Rober Lafore Chapter 11, Page 504