Jack in the Box
Jack in the Box

Reputation: 137

Access data members of another class in overloading operator

I have this operator

Mtx Mtx::operator*(const Vtr &rhs) const
{
Mtx Q(nrows, ncols, 0);

for (int i = 0; i < nrows; ++i) {
    for (int j = 0; j < ncols; ++j) {
        Q.ets[i][j] = 0.0;

        for (int k = 0; k < rhs.length; ++k) {
            Q.ets[i][j] += ets[i][k] * rhs.ets[k];
        }
    }
  }
return Q;
}

I call this operator by M3 = M1 * V1, I receive compiler errors because length and ets[k] in the third loop are private members of class Vtr. How can I access them?

Upvotes: 1

Views: 378

Answers (3)

jxh
jxh

Reputation: 70382

Let Mtx be a friend of Vtr.

 class Vtr {
     friend class Mtx;
     //...
 };

Or let the Mtx::operator* method be a friend.

 class Vtr {
     friend Mtx Mtx::operator*(const Vtr &) const;
     //...
 };

Either of these changes will let your current implementation work without any further changes.

Upvotes: 4

juanchopanza
juanchopanza

Reputation: 227370

Either make Mtx a friend of Vtr or provide public assess to the data, for example

class Vtx {
 public:
  const SomeType& operator[](unsigned int i) const { return ets[i]; }

};

This actually decouples the data access from the underlying implementation, since the operator can be implemented in different ways.

On the other hand, it provides a direct access to the underlying representation, so it adds the constraint that you cannot change the implementation in a way that changes the mapping between a given index and a given element.

Upvotes: 4

Rohit Vipin Mathews
Rohit Vipin Mathews

Reputation: 11787

Friend is your answer!!

Either you can make the class a friend or the function.

But I'm not sure if that is the correct logic for you case.

Mostly if you cant access a variable that means you shouldn't access it.

Check if you are doing correctly with access specifiers. And the only way to go about is friend then use 'friend' function or class.

Upvotes: 2

Related Questions