V
Victor Bazarov
Hello All,
Here is the code:
class Foo {
public:
virtual void bar() const = 0;
};
#include <ostream>
#include <iostream>
class Foo1 : public Foo {
void bar() const { std::cout << "Foo1::bar\n"; }
};
class Foo2 : public Foo {
void bar() const { std::cout << "Foo2::bar\n"; }
};
void foo(const Foo* pFoo)
{
(pFoo ? *pFoo : Foo1()).bar(); // line 19 ************
}
void blah(const Foo& rFoo)
{
foo(&rFoo);
}
int main()
{
blah(Foo2());
}
Line 19 is the line in question. Could you please interpret it for me?
It seems to skip the virtual function dispatch, and attempt to call
the pure function. The common type of *pFoo and Foo1() is 'class Foo',
and the compiler seems to resolve the 'bar' statically, without the use
of virtual function mechanism, as if there is an instance of class Foo
/sliced/ from both original objects. Is that supposed to happen?
Standard chapter and verse would be helpful.
To avoid a pure function call I can implement the base class' member
function 'bar'. The problem is that in that case I get the dynamic
dispatch I need (I expected Foo2.bar() to be called), I am getting the
base class. Is that what *should* happen?
Thanks!
V
Here is the code:
class Foo {
public:
virtual void bar() const = 0;
};
#include <ostream>
#include <iostream>
class Foo1 : public Foo {
void bar() const { std::cout << "Foo1::bar\n"; }
};
class Foo2 : public Foo {
void bar() const { std::cout << "Foo2::bar\n"; }
};
void foo(const Foo* pFoo)
{
(pFoo ? *pFoo : Foo1()).bar(); // line 19 ************
}
void blah(const Foo& rFoo)
{
foo(&rFoo);
}
int main()
{
blah(Foo2());
}
Line 19 is the line in question. Could you please interpret it for me?
It seems to skip the virtual function dispatch, and attempt to call
the pure function. The common type of *pFoo and Foo1() is 'class Foo',
and the compiler seems to resolve the 'bar' statically, without the use
of virtual function mechanism, as if there is an instance of class Foo
/sliced/ from both original objects. Is that supposed to happen?
Standard chapter and verse would be helpful.
To avoid a pure function call I can implement the base class' member
function 'bar'. The problem is that in that case I get the dynamic
dispatch I need (I expected Foo2.bar() to be called), I am getting the
base class. Is that what *should* happen?
Thanks!
V