The University of Iowa
The College of Liberal Arts and Sciences
Department of Computer Science
Lecture/Lab #13
Friends, inheritance
struct organism
{
enum type { plant, animal, fungi };
organism( type t ) : type_( t ) {}
type const type_;
};
struct triangle
{
triangle( double s1, double s2, double s3 );
bool is_valid() const;
double side1;
double side2;
double side3;
};
Prevent users from directly creating instances of type `plant`; implement a function that reads and returns a new `plant` loaded from a stream
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 "Lab13 exercises" poll in #general
Public inheritance establishes is-a relationship between base and derived classes.
A reference to a derived class is implicitly convertible to a reference to a base class.
Base class constructor is always called (implicitly or explicitly) as a part of the derived class constructor.
Base class constructor is called before other data members of the derived class are initialized.
An instance of a base class can be explicitly cast to a derived class using static_cast; if the cast instance isn't in fact a part of the derived object, the cast results in undefined behavior.
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;
};
Complete the class hierarchy 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 "Lab13 exercises" poll in #general