Jump to content
  • Advertisement
Sign in to follow this  
masterbubu

virtual operators c++ probelm

This topic is 3012 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
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).

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!