MC logo

Operator Overloading (Answer)

  Practice Questions

Repeating the declarations:


  #include <iostream.h>
  class Gromitz
  {
       int g;
  public:
       Gromitz(int i=0) { g = i; }
       Gromitz operator+(const Gromitz& gr) const
       {
            return Gromitz(g + gr.g);
       }
       bool operator==(const Gromitz& x) const
       {
            return g == x.g;
       }
       ostream& operator<<(ostream &str) const
       {
            str << g;
            return str;
       }
       int val() const { return g; }
  };
  Gromitz a,b(5);
  void f(Gromitz g);

Say which are valid and which are not.

  1. a = 10;

    This will compile. The first constructor provides a conversion from integer to Gromitz. Assignment of any class type to itself is always provided by default.

  2. a += b;

    This will not compile. The += operation is not defined for Gromitz in any form.

  3. cout << b;

    This will not compile. The operator<< defined in class Gromitz must have the class on the left. The expression b << cout would use it. That is why stream overloads are usually done with top level functions.

  4. a == 7;

    This will compile, using the first constructor as a conversion from integer to Gromitz, then the operator== to compare the two Gromitz values.

  5. f(b);

    This works fine.


<<Function Overloading Question Construction and Destruction I>>