Object Oriented Programming (OOP) - CS304 Power Point Slides Lecture 29
Object Oriented Programming (OOP) - CS304 Power Point Slides Lecture 29
(OOP)
Lecture No. 29
Abstract Class
Shape
draw
calcArea
• Cannot be instantiated
• Can be instantiated
class Shape {
…
public:
virtual void draw() = 0;
}
…
Shape s; // Error!
… Pure Virtual Functions
Rectangle
draw
… Pure Virtual Functions
• Output
Shape destructor called
Result
pShape pShape
Shape Part
Quad Part Quad Part
Rect Part Rect Part
Before After
Virtual Destructors
• Make the base class destructor virtual
class Shape {
…
public:
virtual ~Shape() {
cout << “Shape destructor
called\n”; }
}
…Virtual Destructors
class Quadrilateral : public Shape {
…
public:
virtual ~Quadrilateral() {
cout << “Quadrilateral
destructor
called\n”;
}
}
…Virtual Destructors
class Rectangle : public
Quadrilateral {
…
public:
virtual ~Rectangle() {
cout << “Rectangle destructor
called\n”;
}
}
…Virtual Destructors
• Output
Rectangle destructor called
Quadilateral destructor called
Shape destructor called
Result
pShape pShape
Shape Part
Quad Part
Rect Part
Before After
Virtual Functions – Usage
int main() {
Point p1( 10, 10 ), p2( 30, 30 );
Shape* pShape;
pShape
Dynamic Dispatch
• For non-virtual functions, compiler just
generates code to call the function