Reputation: 198
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
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
Reputation: 208323
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
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