0

I wish to understand how the code below runs. Is aproxy inheriting from mPtr? Is struct array returning a method, aproxy, in struct aproxy?

struct aproxy {
    aproxy( int & r ) : mPtr( & r ) {}  // is this inheritance? 
    void operator = ( int n ) {
        if ( n > 1 ) {
            throw "not binary digit";
        }
        *mPtr = n;
    }
    int * mPtr;
};

struct array {      
    int mArray[10];
    aproxy operator[]( int i) {      
        return aproxy( mArray[i] );   // what does this line do?
    }
};

int main() {
    try {
        array a;
        a[0] = 1;   
        a[0] = 42;      
    }
    catch( const char * e ) {
        cout << e << endl;
    }
}
Raedwald
  • 46,613
  • 43
  • 151
  • 237
Pippi
  • 2,451
  • 8
  • 39
  • 59

2 Answers2

3

is this inheritance?

aproxy( int & r ) : mPtr( & r ) {} 

This is not inheritance, it is the initialization of data member mPtr in a constructor initialization list. You are initializing a pointer to int to point to the address of an int.

return aproxy( mArray[i] );   // what does this line do?

It creates an aproxy instance, initialized with the value of mArray[i], and returns it by value.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
2

No, there is no inheritance here. And you cannot "return a method"; "method" is a colloquial name for a "member function".

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055