Sign in to follow this  
masterbubu

virtual operators c++ probelm

Recommended Posts

masterbubu    181
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,

Share this post


Link to post
Share on other sites
CastorX    132
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).

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this