Jump to content
  • Advertisement
Sign in to follow this  
choffstein

virtual functions question

This topic is 4974 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

Is there anyway that I can make a parent class have a virtual function that the child class is only required to have a "type" of? And by that, I mean only a function of the same name that returns the same type, but not necessarily requires the same parameters? Like an overloaded virtual function, of sorts? Ex:
class A
{
   public:
      virtual void doThing() = 0;
};

class B : public A
{
   public:
      void doThing(int a);
};

class C: public A
{
   public:
      void doThing(float a);
};
Is that possible? Thanks!

Share this post


Link to post
Share on other sites
Advertisement
you would have to do it like this

class A
{
public:
virtual void doThing() = 0;
};

class B : public A
{
public:
void doThing(){doThing(13287);}
void doThing(int a);
};

class C: public A
{
public:
void doThing(){doThing(165.145f);}
void doThing(float a);
};

Share this post


Link to post
Share on other sites
Why would you want such a function? You wouldn't be able to use it polymorphically.

Share this post


Link to post
Share on other sites
What you're hoping are virtual functions are actually overloaded functions.


void doThing();
void doThing(int a);
void doThing(float a);


are 3 different, unrelated functions.

If you try to instantiate an object B or C, the compiler will deny you because doThing() is a pure virtual and has not been defined. Instead, entirely new functions doThing(int a) and doThing(float a) have been defined.

What is this for anyway?

Share this post


Link to post
Share on other sites
You could try having the function declared with a default value:

class A
{
virtual void doThing(int P=0) = 0;
};

class B : A
{
virtual void doThing(int P);
};


A *b = new B;
B->doThing(5);



However, that's a bit of a hack.

Also you should never specify different default parameters in a derived virtual function. If you do this the parameter defalt will be different if function is called polymorphically than if it's called statically.

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!