The University of Iowa
The College of Liberal Arts and Sciences
Department of Computer Science
Lecture/Lab #14
(Run-time) polymorphism, abstract classes
class car():
def __init__( self,
make_n_model,
year ):
self.make_n_model \
= make_n_model
self.year = year
class truck( car ):
def __init__( self,
make_n_model,
year,
capacity ):
super().__init__(
make_n_model,
year )
self.capacity = capacity
struct car {
car( string make_n_model,
int year )
: make_n_model( make_n_model )
, year( year )
{}
string make_n_model;
int year;
};
struct truck : car { // truck is-a car
truck( string make_n_model,
int year, double capacity )
: car( make_n_model, year )
, capacity( capacity )
{}
double capacity;
};
aka Dynamic Binding
Ability to vary, at run-time, the behavior of a member function call depending on the type of the object on which it is called
Polymorphic functions have to be explicitly marked with the virtual keyword
Polymorphic functions have to be explicitly marked with the virtual keyword in the base class and marked with the override keyword when overridden
A derived polymorphic function must have the exact same signature as the base-class function it overrides*
It is legal for a derived class to define a function with the same name as a virtual function in its base class but with a different parameter list
A polymorphic function designated as final cannot be overridden.
class car():
def start( self ):
print( "starting car" )
class truck( car ):
def start( self ):
print( "starting truck" )
class sedan( car ):
def start( self ):
print( "couldn't start" )
def start_car( c ):
c.start()
start_car( car() )
start_car( truck() )
start_car( sedan() )
struct car {
virtual void start() const {
std::cout << "starting car\n";
}
};
struct truck : car {
void start() const override {
std::cout << "starting truck\n";
}
};
void start_car( car const& c ) {
c.start();
}
int main() {
start_car( car() );
start_car( truck() );
start_car( sedan() );
}
Implement `move_by` method in the derived class with the run-time behavior to match the corresponding test cases
Open the exercise template
Write your code, press Run to test
When you're done, grab your Repl's link and send it as a direct message to me (agurtovoy)
Click on the corresponding option in the "Lab14 exercises" poll in #general
Pure virtual function — a polymorphic function with no implementation
A pure virtual function is designated by writing = 0 in place of a function body
Classes with at least one pure virtual function are called abstract
Abstract classes cannot be instantiated
Classes that contain only pure virtual functions are called pure abstract classes