Vikash
Vikash

Reputation: 77

How does parenthesis operator overlaoding work in C++?

I've following code:

#include <iostream>
#include <cassert>

class Matrix
{
private:
    double m_data[3][3]{};

public:
    double& operator()(int row, int col);
};

double& Matrix::operator()(int row, int col)
{
    assert(col >= 0 && col < 3);
    assert(row >= 0 && row < 3);

    return m_data[row][col];
}

int main()
{
    Matrix matrix;
    matrix(1, 2) = 4.5;
    std::cout << matrix(1, 2) << '\n';

    return 0;
}

I'm wondering how does following line assigns the 4.5 to m_data[1][2].

matrix(1, 2) = 4.5;

Actually, there is no assignment inside the function double& operator()(int row, int col). It has only return m_data[row][col]; statement. Shouldn't it just return value at m_data[1][2]. In that case it would be 0 by default.

Upvotes: 1

Views: 76

Answers (1)

This function:

double& Matrix::operator()(int row, int col)

return a reference of a double variable, not just a value.

matrix(1, 2) = 4.5;

matrix(1, 2) returns a reference of that variable, and that reference get assigned a value, that is 4.5

Upvotes: 2

Related Questions