The University of Iowa
The College of Liberal Arts and Sciences
Department of Computer Science

Programming Languages and Tools:

CS:3210:0001

Lecture/Lab #12

Programming with C++

Inheritance, (run-time) polymorphism

Warm up

  • How do you define a class member function outside of the class definition itself?

  • Is the following a valid C++ program?

struct resource;
struct lock
{
    struct key {}; // can we nest types?
    lock( resource& r ) : r_( r ) {}    
    resource& unlock( key const& ) { return r_; }
private:
    resource& r_;
};
struct car
{
    car( std::string const& make ) : make( make ) {}
    void start() { std::cout << "Starting...\n"; }

    std::string const make;
};

Exercise 1

Define all class member functions and types outside of the provided class definition

  • 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 "Lab12 exercises" poll in #general

Inheritance 101

struct car {
    car( std::string const& make, 
    	std::string const& model, 
    	int year );

    std::string make;
    std::string model;
    int year;
};


struct truck : car { // truck is-a car
    truck( std::string const& make, 
    	std::string const& model, 
    	int year, double capacity );

    double capacity;
};

Inheritance summary

  • 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 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.

Exercise 2

Complete the class hierarchy as outlined in the exercise's comments

  • 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 "Lab12 exercises" poll in #general

(Run-rime) Polymorphism

struct car {
    car( std::string const& make, 
    	std::string const& model, 
    	int year );

    void print( std::ostream& ) const;
};


struct truck : car { // truck is-a car
    truck( std::string const& make, 
    	std::string const& model, 
    	int year, double capacity );

    void print( std::ostream& ) const;
};


std::ostream& operator<<( std::ostream& out, car const& c ) {
    c.print( out );
    return out;
}

Programming with C++, Fall 2019, Lecture #12

By Aleksey Gurtovoy

Programming with C++, Fall 2019, Lecture #12

Inheritance, (run-time) polymorphism

  • 529