Indirection (dereference) operator overloading

Hi,

I'm trying to overload operator*() for a class I have created but it doesn't work as I expect.

This is how the implementation looks:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>

class MyInt
{
public:
	MyInt(int _int) : m_Int(_int) {}
	~MyInt() {}

	int& operator* () { return this->GetInt(); }
	
	int& GetInt() { return m_Int; }

private:
	int m_Int;
};


int Func(MyInt* p)
{
	return *p;                // this doesn't compile!!!
	//return p->operator*();  // ...but this does (and runs as well)
}


int main()
{
	MyInt* pInt = new MyInt(5);
	int val = Func(pInt);
	std::cout << val << std::endl;

	return 0;
}


I can't figure out why the overloading doesn't work. It works if I explicitly use the operator. Does the compiler get confused when not explicity using the operator?
What am I doing wrong?

I use VC++ 2008 Express Ed.
Use
1
2
3
4
int Func(MyInt* p)
{
	return **p;
}


You have to dereference it twice, first you get MyInt from pointer, and second you call operator*().
Yes of course. I really didn't have a clear idea about what I was doing. The dereference operator works on a MyInt type, not a pointer to a MyInt as I first thought.

Thanks for your answer. That cleared things up.
Topic archived. No new replies allowed.