I want to overload array opperator (->) as a standard operator for pointers and additionaly whant to show somethink on the console.
And I did ...
Gamer.h file (Gamer class with nested Collecion class) :
class Gamer {
class Collection
{
public:
Collection();
Collection* operator->();
}
public:
Gamer();
Collection *deck;
}
Gamer.cpp
...
Gamer::Collection* Gamer::Collection::operator->()
{
cout << "Pointer on deck >> " << this << endl;
return this;
}
...
main.cpp - here i declare and alloc memory for Gamer object who have collection field inside (as pointer)
Gamer *gamer;
Gamer::allocGamer(gamer);
When i want to use overloaded array opperand I can't do :
gamer->deck->();
But I can :
gamer->deck->operator->();
The question is why I cant just call gamer->deck->(); and have to call gamer->deck->operator->(); instead ?
And second question - How I should overload arrow opperand to have direct access to overloaded opperand like gamer->deck->(); ?
operator->
is a binary operator. "binary operator" means it takes two operands. For example:It is not possible to write
deck->
without a second operand.Calling it as
deck->operator->();
is a bit of a hack, which is legal but you should not design your code to rely on that because it will be confusing to readers.The purpose of overloading
operator->
is so that you can writedeck->foo
. If you do not want to writedeck->foo
then you should not useoperator->
for whatever you are trying to do.For example, if you just want a function to retrieve
foo
then call itget_foo()
, notoperator->()
.Note:
Gamer::allocGamer(gamer);
is suspicious (ifallocGamer
takes its parameter by value it's a bug, and if it takes it by reference then this is an unusual idiom that will be confusing to people reading your code). Your code will be simpler if you don't use memory management, and don't force users of your class to use manual memory management either.