virtual operators c++ probelm

Started by
2 comments, last by phresnel 14 years ago
Hi
[SOURCE]

class A
{
	public:
	A(){}
	~A(){}
	virtual operator const char*() const
	{
		return "A";
	}

};

class B : public  A
{
public:
	B(){}
	~B(){}

	  operator const char*() const
	 {
              return "B";
	 }
};

int main()
{
   B b;
   A* a = &b;
   const char* str = (const char*)a;
}

[/SOURCE]
I debug the code and none of the operators get called. (if "a" were not a pointer it works fine ). if you type:
[SOURCE]
const char* str = a->operator const char*(); // This works fine
[/SOURCE]
Why the first version did not worked? tnx,
Advertisement
This will work:

const char* str = (const char*)*a;

The problem with yours:
const char* str = (const char*)a;
is that you convert a pointer (to an object) to const char*, but you have to convert the object itself (the compiler will call the operator you wrote to do that).
shame on me I have not noticed that

tnx man
For the future just so you know,

p->operator Δ ()


is the same as

(*p) Δ

This topic is closed to new replies.

Advertisement