Jump to content
  • Advertisement
Sign in to follow this  
The C modest god

Two questions in C++

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

If I have the following:
class A {
};
class B: public A {
};
class C {
  public:
     void foo (A& Arg); // <= 1
     void foo (B& Arg); // <= 2
}
B b;
C c;

c.foo (b);
which foo will be called, 1 or 2? Is there a problem doing this? Assuming that in the previous example 2 will be called and there is no problem. Consider the following code:
class A {
};
class B: public A {
  public:
     void foo2 (C& Arg); // <= 1
     void foo2 (D& Arg); // <= 2
};
class C {
  public:
     virtual void foo (B& Arg);
}
class D: public C {
  public:
     void foo (B & Arg) { Arg.foo2 (*this); };
}

D d;
C * pC;
B b;

pC = &d;

pC->foo (b);

Will 2 be called? Is there a problem with what I did? I would appreaciate your answers. Thanks in advance.

Share this post


Link to post
Share on other sites
Advertisement
Why don't you ask your compiler? You have the code, why not add tracing functions, or just follow the code flow in the debugger to find out?

Share this post


Link to post
Share on other sites
I don't know if "just ask your compiler" is always the best advice. If the code ever has any undefined behavior, then it might seem to work on their compiler, but still be bad code. Not that this is one of those times, but anyway.

The first example will call foo #2 - when the compiler is figuring out which version of an overloaded function to use, it will always pick an exact match first.

In the second example, foo2 #2 will be called. The whole point of the virtual table is that the derived class's (D in this case) functions will still be called even when your object of type D is casted as something else (C).

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!