Re: Need some information about function hiding
Am 16.02.2011 20:56, schrieb abhijeet:
Here is some piece of code -
class A
{
public:
explicit A(){printf("constructing A\n");};
};
class base
{
public:
virtual void foo(int i) {printf("inside base\n");};
};
class derived : public base
{
public:
virtual void foo(A&i) {printf("inside derived\n");};
};
You are mixing here two orthogonal mechanisms in C++: Function
*overriding* [even though derived::foo(A&) does not override
base::foo(int)] and function *overloading*.
main()
{
base *ptr = new derived();
ptr->foo(1);
}
"test.cpp" 21 lines, 607 characters
CC test.cpp
"test.cpp", line 14: Warning: derived::foo hides the virtual function
base::foo(int).
1 Warning(s) detected.
a.out
inside base
I understand that when I replace the argument type for a function in
derived type, original defn gets hidden.
Yes. And if the function types are the same, the version of derived
would override the version of base. This is not the case here, though.
But hiding is a compile-time thing, no runtime-thing.
Only thing I find really interesting is why in case we have types
which can not be converted by promoting (like I can promote int to
float) definitions are still hidden.
Your program does not take advantage of overriding here, so your
presentation of the function declaration derived::foo(A&) is a red
herring in this example. You could omit it without influencing the
observable effects of the program.
Also, with default rules I am having hard time explaining execution
which is above on sun solaris CC.
The runtime behaviour is simple: You are creating an object of dynamic
type derived and produce via implicit conversion a base*. Now you are
statically invoking base::foo(int), which is fine, because a derived
class also provides the functions from the base class. Derived does not
override this function, so the example code should output:
inside base
This is exactly what you are reporting.
Let me add that I notice the lack of a virtual destructor in base. In
your example code you are not deleting the pointer, but in a real-world
program you probably would. But doing this via the base class pointer of
an object of a derived class type without a virtual base class
destructor leads to undefined behaviour.
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]