Re: Isn't this a polymorphic call?
On May 29, 10:30 am, "Alf P. Steinbach" <al...@start.no> wrote:
* James Kanze:
On May 29, 2:15 am, "A. Bolmarcich" <agge...@earl-grey.cloud9.net>
wrote:
On 2008-05-28, Arindam <arindam.muker...@gmail.com> wrote:
On May 29, 2:14 am, Victor Bazarov <v.Abaza...@comAcast.net> wrote:
Arindam wrote:
#include <cstdio>
struct Test {
void bar() {
foo();
}
private:
virtual void foo() {
printf("Test\n");
}
};
struct Test2 : public Test {
void foo() {
printf("Test2\n");
}
};
int main(int argc, char* argv[])
{
Test2 v;
v.bar();
}
Does the call to v.bar() amount to a polymorphic
invocation of foo()?
Have you tried it? If you have, what happened? If not, why not?
Yes - it prints Test2. So this should be polymorphic right?
It is not polymorphic according to the inventor of C++, who
wrote in "The C++ Programming Language (Third Edition)":
"To get polymorphic behavior in C++, the member functions
called must be virtual and objects must be manipulated
through pointers or references. When manipulating an
object directly (rather than through a pointer or
reference), its exact type is known by the compiler so that
run-time polymorphism is not needed."
And? He's calling foo() through a pointer (this), and the
call is resolved polymorphicly.
I think the question is (nearly) meaningless. The standard
doesn't guarantee how any call is resolved at the machine code
level. E.g. in this case the compiler may inline everything
so that there's no call instruction.
I almost answered like that myself. The real question is: what
does he mean by polymorphic behavior. In the end, whatever code
the compiler generates, however, the call must resolve to the
dynamic type, and not the static type, because the function is
virtual. How the compiler ensures this is its business.
And that, IMHO, is the real definition of polymorphism; the
behavior corresponds to that of the dynamic type of the object.
(Of course, we both agree that if the compiler can determine
what the dynamic type will be, then it can generate different,
and typically more efficient, code than if it can't.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34