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

Programming Languages and Tools:

CS:3210:0001

Lecture/Lab #9

Programming with C++

Operator overloading, const, references

Warm up

  • What's a user-defined type?

  • What does a constructor do?

  • Is this valid C++? If so, what does it do?

struct point { int x{0}, y{0}, z{0}; };
point p = { .z=10 };
  • What's wrong with the following code?

struct point { 
    point( int x, int y, int z ) {}
    int x;
    int y;
    int z;
};

point p = { 5, 17, -10 };

Operator overloading

  • Ability for C++ operators to have user-defined meanings on user-defined types
  • Most most built-in operators in C++ can be overloaded.
  • Overloaded operators are just functions with predefined names.
  • An overloaded operator is called an operator function.
  • We can't define our own custom operators that don't already exist in the language.
  • Overloaded operators keep their precedence.

Exercise 1

Define missing `point` operators to make the program compile and pass the tests

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

const

A keyword that tells the compiler that the object or variable is not modifiable

int main() {
    int const i = 7;
    i = 10; // error
    ++i; // error

    point const p( 0, -1 );
    p.x = -1; // error
}

References

  • A reference is an alias to another object/variable

  • When we define a reference, we bind the reference to its initializer

  • A reference variable cannot be left uninitialized

  • Once initialized, a reference remains bound to its initial object. There is no way to rebind a reference to refer to a different object

  • All operations on a bound reference are operations on the object to which the reference is bound.

  • A reference type is an example of a compound type; a compound type can be used anywhere where a built-in type can be used.

Exercise 2

Implement `add_to` function that takes two points and adds the second point to the first one

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

Const references

  • const reference == a reference to a const object

  • Primarily used to optimize away unnecessarily copying of objects

  • May refer to an object that is not const

Made with Slides.com