1

According to this post:

The array subscription operator is a binary operator which must be implemented as a class member.

Then it provides an example:

class X {
        value_type& operator[](index_type idx);
  const value_type& operator[](index_type idx) const;
  // ...
};

Is it possible to define this operator as a member outside of the class definition?

Community
  • 1
  • 1
  • 1
    The only real class _declaration_ is an empty forward declaration. The code posted above is a class definition, not declaration, and I wanted to know if we could define it outside the class{} block. –  Feb 24 '14 at 07:56
  • @Bathsheba class *definition* is the correct term here. Note that a class definition is also a declaration, which is nice and confusing. – juanchopanza Feb 24 '14 at 07:58
  • Supposing the post you linked is correct, and that is very likly as it is community wiki and often seen, then it is not possible to do so. – MatthiasB Feb 24 '14 at 08:00
  • 1
    It's possible to _define_ `operator[]` outside of the class definition but it still has to be a class member and therefore _declared_ in the class definition. – CB Bailey Feb 24 '14 at 08:05

1 Answers1

2

Yes, you can declare it into the class and define it into another translation unit (or same unit) like the following

main.cpp

#include <iostream>
using namespace std;

class myClass {
    public:

    int operator[](int idx);
};

// Definition outside of the class
int myClass::operator[](int idx) {
    return 42;
}

int main() {
    myClass obj;

    cout << obj[55];

    return 0;
}

Or something like the following

main.cpp

#include <iostream>
#include "header.h" <--
using namespace std;

int main() {
    myClass obj;

    cout << obj[55];

    return 0;
}

header.h

#pragma once

class myClass {
    public:

    int operator[](int idx);
};

header.cpp

#include "header.h"

// Definition outside of the class
int myClass::operator[](int idx) {
    return 42;
}

Just remember the ODR - One Definition Rule: in any translation unit a template, type, object or function shall have no more than one definition.

Marco A.
  • 43,032
  • 26
  • 132
  • 246