Lecture Week10-11 Abstract Classes-up2
Lecture Week10-11 Abstract Classes-up2
Programming
Abstract Classes
• Abstract Classes
– Pure Virtual Function
– Abstract Classes
Pure Virtual Function
• A pure virtual function is a virtual function
whose declaration ends with = 0 e.g.
class Data {
// ...
virtual void function() = 0;
// ...
};
OR
class Data {
// ...
virtual float calculateArea() = 0;
// ...
};
40
Pure Virtual Function
The equal sign here has nothing to do
with assignment; the value 0 is not
assigned to anything.
The =0 syntax is simply how we tell
the compiler that a virtual function will be
pure.
41
Pure Virtual Function
• How can we make it clear to someone
using our family of classes that we don’t
want anyone to instantiate objects of the
base class?
– We could just say this in the documentation, and
count on the users of the class to remember.
• How can we can do that? By placing at
least one pure virtual function in the base
class.
42
Example 8 – Abstract Class
45
Example 9- Attempting to instantiate an
object of an abstract class: Output Error
Example 9- Attempting to instantiate
an object of an abstract class: Output
Error
• Now if in main() you attempt to create objects of
class Base, the compiler will complain that you’re
trying to instantiate an object of an abstract class. It
will also tell you the name of the pure virtual
function that makes it an abstract class.
in
Abstract Class
• If a subclass of an Abstract Class needs to be
instantiated, it has to implement each of the virtual
functions
– which means that it supports the interface declared by the ABC.
• Failure to override a pure virtual function in a
derived class, then attempting to instantiate
objects of that class, is a compilation error.
• If we do not override the pure virtual function in
derived class, then derived class also becomes
abstract class.
• Classes that can be used to instantiate objects
are CS212 Object Oriented Programming in
C++
Example 11- Abstract Class
Polygon
Implementation of
Virtual Function in
Derived class
Pure Virtual definition
Base
Derv1 Derv2