Course Materials

OOP - Week 3, Lecture 1: Object Parameters and Returning Objects

Comparing Two Objects

Suppose you have two rectangles and want to know which one is larger. With what you know so far, main has to pull the numbers out of both objects:

Rectangle r1(4, 3);
Rectangle r2(2, 5);

if (r1.getWidth() * r1.getHeight() > r2.getWidth() * r2.getHeight())
    cout << "r1 is larger" << endl;

This works, but it is long, it must be repeated every time you compare two rectangles, and main has to know how the area of a rectangle is calculated. That knowledge belongs inside the class.

We would rather write:

if (r1.isLargerThan(r2))
    cout << "r1 is larger" << endl;

For that, a member function must be able to receive another object as a parameter. In this lecture we use a new class, Rectangle, with everything you learned in Week 2: private data members, constructors, setters and getters. We add a member function with a default parameter, and member functions that take and return objects.

1. Default Parameters in Member Functions

You revised default parameters in Week 1 and used them in a constructor in Week 2, Lecture 2. They work the same way in any member function:

void scale(int factor = 2) {
    setWidth(width * factor);
    setHeight(height * factor);
}
Rectangle r(4, 3);
r.scale();                   // no argument, so factor is 2
r.scale(3);                  // factor is 3

The same rules apply: default values are filled in from the right, and arguments are matched from the left.

2. A Member Function with an Object Parameter

A member function can take another object of the same class as a parameter:

bool isLargerThan(const Rectangle& other) {
    return width * height > other.width * other.height;
}
Rectangle r1(4, 3);
Rectangle r2(2, 5);
r1.isLargerThan(r2);         // 12 > 10, so true

Notice that the function repeats width * height instead of calling area(), which returns the same value. The warning below explains why.

Inside the function there are two rectangles, and the name tells you which one:

In the functionThese are the data members ofIn the call r1.isLargerThan(r2)
width, heightthe object that called the function isLargerThanr1
other.width, other.heightthe object that was sent as a parameter to isLargerThanr2

Because the function is inside the class, it can read the private members of other, just as the copy constructor did in Week 2, Lecture 3. Any object of the class can read the private members of any other object of the class.

Why const Rectangle& other?

  • &: the argument is passed by reference, so the object is not copied. With Rectangle other (by value) the copy constructor would run every time you call the function.
  • const: a promise that the function will not change other. It is the same const explained in Week 2, Lecture 3. We study it fully in Week 4.

Warning: With const Rectangle& other, you can read other.width, but you cannot call other.area() yet. The compiler reports an error that says area() is not marked const (the exact words depend on your compiler). area() does not promise that it leaves the object unchanged, so the compiler will not let a const object call it. In Week 4 you will learn to mark such functions const. Until then, read the data members directly.

The same pattern works for any class. For Date:

bool isBefore(const Date& other) {
    if (year != other.year)
        return year < other.year;
    if (month != other.month)
        return month < other.month;
    return day < other.day;
}
Date a(7, 10, 2023);
Date b(19, 9, 2026);
a.isBefore(b);               // true: 2023 is before 2026

3. Returning an Object

A member function can also return an object. The function creates a new object and gives it back to the caller:

Rectangle add(const Rectangle& other) {
    Rectangle result(width + other.width, height + other.height);
    return result;
}
Rectangle r3 = r1.add(r2);   // r3 is 6 x 8
  • r1 and r2 are not changed. add builds a new rectangle from them.
  • The return type is Rectangle, so the object is returned by value: the caller receives a new object. Section 4 explains which constructors run.
  • Do not return a reference to a local object such as result. A local object is destroyed when the function ends, so the reference would point to an object that no longer exists.

4. Which Constructor Runs?

In Week 2, Lecture 3 you saw that passing an object by value runs the copy constructor. The same rules apply to member functions, and now that an object can also be returned, here is the whole picture:

What the function doesExampleWhat runs
Takes the object by referenceisLargerThan(const Rectangle& other)Nothing. other is another name for the argument, so no new object is created.
Takes the object by valueisSmallerThan(Rectangle other)The copy constructor creates other from the argument. When the function ends, the destructor destroys other.
Returns an object by valueRectangle add(...) returns resultThe returned object is created from result, which is a job for the copy constructor. The caller’s r3 is then created from the returned object.

The program in the next section prints a message from every constructor and from the destructor, so you can see each row of the table happen. Its function isSmallerThan takes the object by value.

This is one more reason to pass objects by const reference when the function only needs to read them: it avoids creating and destroying a copy on every call.

5. Putting It Together

This program uses everything from this lecture: scale has a default parameter, isLargerThan takes an object by reference, isSmallerThan takes an object by value, and add takes an object and returns a new one. It also prints a message from every constructor and from the destructor. Click each line of output to see what caused it.

Rectangle with object parameterscode/oop/week-03/rectangle-1
has a note
#include <iostream>
using namespace std;

class Rectangle {
private:
    int width, height;

public:
    Rectangle(int w, int h) {                   // parameterized constructor
        width = 1;
        height = 1;
        setWidth(w);
        setHeight(h);
        cout << "  constructor " << width << " x " << height << endl;
    }
    Rectangle(const Rectangle& other) {         // copy constructor
        width = other.width;
        height = other.height;
        cout << "  copy constructor " << width << " x " << height << endl;
    }
    ~Rectangle() {                              // destructor
        cout << "  destructor " << width << " x " << height << endl;
    }

    void setWidth(int w) {
        if (w < 1)                              // validation
            return;
        width = w;
    }
    void setHeight(int h) {
        if (h < 1)                              // validation
            return;
        height = h;
    }

    int getWidth() {
        return width;
    }
    int getHeight() {
        return height;
    }

    int area() {
        return width * height;
    }

    void print() {
        cout << width << " x " << height << " (area " << area() << ")" << endl;
    }

    void scale(int factor = 2) {                // default parameter
        setWidth(width * factor);
        setHeight(height * factor);
    }

    bool isLargerThan(const Rectangle& other) { // object parameter, by reference
        return width * height > other.width * other.height;
    }

    bool isSmallerThan(Rectangle other) {       // object parameter, by value
        return width * height < other.width * other.height;
    }                                           // other is destroyed here

    Rectangle add(const Rectangle& other) {     // returns an object
        Rectangle result(width + other.width, height + other.height);
        return result;
    }
};

int main() {
    Rectangle r1(4, 3);
    Rectangle r2(2, 5);

    if (r1.isLargerThan(r2))                    // by reference: nothing is copied
        cout << "r1 is larger than r2" << endl;

    if (r1.isSmallerThan(r2))                   // by value: r2 is copied
        cout << "r1 is smaller than r2" << endl;
    else
        cout << "r1 is not smaller than r2" << endl;

    Rectangle r3 = r1.add(r2);                  // r1 called add, r2 was sent as a parameter
    r3.print();                                 // 6 x 8

    r1.scale();                                 // no argument, so factor is 2
    r1.print();                                 // after scale()
    r1.scale(3);                                // factor is 3
    r1.print();                                 // after scale(3)

    return 0;
}                                               // destructors run here
Terminal
g++ main.cpp -o app
./app
Tip: click a line of output to jump to the code that printed it.Output hidden. Try it yourself first.

Notice that there is no copy constructor line after constructor 6 x 8. When a function returns an object, the copy constructor is supposed to run, but the compiler usually skips the copy and builds the object directly in its final place. Since C++17, the copy into r3 is skipped by the rules of the language. The compiler can skip the copy from result only when it is clear which object is returned, for example one local object such as result. If the function returns one of two different objects depending on a condition, a real copy usually happens.