Sign in to follow this  

virtual operators c++ probelm

This topic is 2797 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
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

This topic is 2797 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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