Two questions in C++

Started by
1 comment, last by pinacolada 18 years, 8 months ago
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.
It's all about the wheel.Never blindly trust technoligy.I love my internal organs.Real men don't shower.Quote:Original post by Toolmaker Quote:Original post by The C modest godHow is my improoved signature?It sucks, just like you.
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?
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).

This topic is closed to new replies.

Advertisement