LaLeX
LaLeX

Reputation: 198

How to overload operator= to return pointer to a member?

Having something like the following code (simplified):

struct MyStruct {
    int member1;
    int member2;
};

class MyClass { 
    MyStruct *data;
}


MyClass obj;

// put obj.data in pstruct  
// so obj.data->element1 is the same as pstruct->element1
MyStruct *pstruct = obj;

I don't want to create a copy of obj.data but return the same pointer so if i make a change in pstruct->member1 the change is the same in obj.data->element1 (and the opposite).

Is this possible?

Thanks

Upvotes: 1

Views: 562

Answers (4)

Robᵩ
Robᵩ

Reputation: 168616

You can do what you want with a conversion operator, but I'd prefer to see you write a getter method. This avoids issues with implicit conversions.

class MyClass {
private:
    MyStruct *data;
public:
    MyStruct* GetData() const { return data; }
};


int main () {
  MyClass obj;
  MyStruct *pstruct = obj.GetData();
  MyStruct *pstruct2;
  pstruct = obj.GetData();
}

Upvotes: 1

The first thing is that you cannot overload operators for pointers, the good thing is that you don't need to, you just need to assign pointers appropriatedly:

MyClass obj;
MyStruct *pstruct = obj.data; // Assuming that `data` is accessible here

If you don't have access to the internal data member, you will need to either provide access (a member function that returns the pointer --breaks encapsulation), or make the calling code a friend of MyClass to grant access to the internal type (still breaks encapsulation, just a bit less).

Upvotes: 2

sth
sth

Reputation: 229563

Sounds like you want a conversion operator that creates a MyStruct* from a MyClass:

class MyClass {
    MyStruct *data;
public:
    operator MyStruct*() {
       return data;
    }
};

Upvotes: 7

Beta
Beta

Reputation: 99084

No problem.

MyClass obj;

MyStruct *pstruct = obj.data;

Upvotes: 2

Related Questions