I cannot believe that I am writing this, because it concerns something that I believe that I understood properly years ago. The code below will not compile in Visual Studio 2005 because it claims that "function does not take 1 arguments". Surely this is a bug in the compiler ! Can overloading really not be done on functions that are inherited ? The code compiles if I supply both functions within the same class.
Could somebody please try this and see if it works. If not which rule of C++ have I failed to grok.
if you're going to overload a function it has to have the same function prototype (name, return type, parameters, modifier) and the base class function must be declared virtual
Having a function with the same name in the derived class the way that you've done it hides the one in the base class so it cant be called on a derived object
Thanks for the reply. It is really appreciated, but I don't think the problem is anything to do with not being declared virtual. I have continued investigating the problem, and I think I found the answer, which is not a bug in Visual Studio compiler. I have managed to use C++ for years without being aware of this. I have pasted below the explanation and solution.
I have another question though - is this behaviour something that changed with the evolution of C++ ? After all 'using' keyword was not in the original C++. I still can't believe that I have used C++ for so long without knowing this ! I wonder whether when I learnt C++ if things were different.
------->>
A member function named f in a class A will hide all other members named f in the base classes of A, regardless of return types or arguments. The following example demonstrates this:
struct A {
void f() { }
};
struct B : A {
void f(int) { }
};
int main() {
B obj_B;
obj_B.f(3);
// obj_B.f();
}The compiler would not allow the function call obj_B.f() because the declaration of void B::f(int) has hidden A::f().
To overload, rather than hide, a function of a base class A in a derived class B, you introduce the name of the function into the scope of B with a using declaration. The following example is the same as the previous example except for the using declaration using A::f:
struct A {
void f() { }
};
struct B : A {
using A::f;
void f(int) { }
};
int main() {
B obj_B;
obj_B.f(3);
obj_B.f();
}
Because of the using declaration in class B, the name f is overloaded with two functions. The compiler will now allow the function call obj_B.f().
class A{
public:
void foo(){cout << 1 << "\n";}
};
class B : public A{
public:
void foo(int x){cout << x << "\n";}
};
int main()
{
A a;
B b;
a.foo();
b.A::foo();
std::cin.get();
}
Thanks very much for that. I hope it did change. Wouldn't like to think I have used C++ for so long without being aware of this. I was sure overloading just depended on the signature.