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

Programming Languages and Tools:

CS:3210:0001

Lecture/Lab #13

Programming with C++

(Run-time) polymorphism, destructors

Warm up

  • Is the following a valid C++ program?

struct car
{
    struct engine {
        engine( car& c ) : car_( c ) {}
        car& car_;
    };

    engine& open_hood();
    void swap_engine( engine& );

private:
    engine engine_{ *this };
};

engine& car::open_hood() { return engine_; }
void car::swap_engine( engine& )
{
    // ...
}

Exercise 1

Fix all compilation errors while keeping the class member definitions outside of the class

  • 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

(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;
}

Exercise 2

Complete the class hierarchy with 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 "Lab13 exercises" poll in #general

Destructors

struct car
{
    car() { std::cout << "car constructed" << std::endl; }
    ~car() { std::cout << "car destructed" << std::endl; }
};

int main() {
    car c;
}
  • A special member function that is called right before the object is destroyed (e.g. when the object goes out of scope)

  • The primary purpose is to free the resources that the object may have acquired during its lifetime

Made with Slides.com