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

Programming Languages and Tools:

CS:3210:0001

Lecture/Lab #11

Programming with C++

Friends, inheritance

Warm up

  • What's the difference between enum and enum class?

  • What's the difference between struct and class?

  • Is the following a valid C++ program?

int main() {
    int n = 42;
    int& r;
    r = n;
    std::cout << r << std::endl;
}
  • How about this one?

auto square( int n ) { return n * n; }

int main() {
    int& i = 17;
    std::cout << i << std::endl;

    int& j = square( 2 );
    std::cout << j << std::endl;
}

Exercise 1

Modify a rational number implementation according to the exercise 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 "Lab11 exercises" poll in #general

friend(s)

struct point {
    point() : x_( 0 ), y_( 0 ) {}
    point( int x, int y ) : x_( x ), y_( y ) {}

    int x() const { return x_; }
    int y() const { return y_; }

private:
    int x_;
    int y_;
};

std::ostream& operator<<( std::ostream& out, point const& p )
{
    return out << "(" << p.x_ << ", " << p.y_ << ")";
}

int main() {
    point p( 17, -3 );
    std::cout << p << std::endl;
}

Inheritance

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( std::string const& make, 
    	std::string const& model, 
    	int year, double capacity );

    double capacity;
};

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

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

By Aleksey Gurtovoy

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

Friends, inheritance

  • 540