Re: non-virtual call to a virtual function using pointer to member
{ Edits: removed quoted clc++m banner. Please remove manually if your
software doesn't. -mod }
On May 29, 6:10 pm, archimed7592 <archimed7...@gmail.com> wrote:
On May 29, 6:47 am, Salt_Peter <pj_h...@yahoo.com> wrote:
On May 28, 3:19 pm, archimed7592 <archimed7...@gmail.com> wrote:
Hi.
for example i have base class A and dirved class B:
struct A
{
virtual void f() { std::cout << "A::f()" << std::endl; }
};
struct B : public A
{
void f() { std::cout << "B::f()" << std::endl; }
};
int main()
{
B b;
A *a = &b;
a->f(); // virtual call. calls B::f()
a->A::f(); // non-virtual call. calls A::f()
A::* pf;
not in C++ its not, try:
void (A::*pf)() = &A::f;
(a->*pf)();
pf = &A::f();
(a->*pf)(); // virtual call. calls B::f()
pf = /* ??? */; // what should i write here for desired effect(non-
virtual call)
Why? You have 2 interfaces to your class. One is via pointer to
base and the other is to the static type itself. Why are you
attempting to break your own interfaces? Provide a non-virtual
function instead and look up 'Non-Virtual idiom' for a solution
involving private virtual functions.
read:http://www.gotw.ca/publications/mill18.htm
It is only task for my brain... nothing else ;)
Question is: is there Standard-conforming C++ code, that does "non-
virtual call" through pointer-to-member.
I think, answer is negative. But, maybe I'm wrong?
I already answered your question, if you prefer your interfaces to
perform a non-virtual call, then design your interface(s) in
consequence. One interface is provided via pointer to base, the other
is the object's interface.
#include <iostream>
class A
{
public:
virtual void vf()
{
std::cout << "A::vf()\n";
}
void f()
{
std::cout << "A::f()\t";
A::vf();
}
void foo()
{
std::cout << "A::foo()\t";
vf(); // virtual !!!
}
};
class B : public A
{
private:
void vf() { std::cout << "B::vf()\n"; }
public:
void f()
{
std::cout << "B::f()\t";
vf();
}
};
int main()
{
B b;
A *a = &b;
// B::vf() is private but *not* to a base pointer
// the virtual call is *not* using B's interface
a->vf(); // virtual, calls B::vf()
a->A::f(); // nv calls A::f(), A::vf()
a->A::foo(); // nv calls A::foo(), B::vf()
void (A::*pf)() = &A::vf;
(a->*pf)(); // virtual calls B::vf()
pf = &A::f;
(a->*pf)(); // nv calls A::f(), A::vf()
pf = &A::foo;
(a->*pf)(); // nv calls A::foo(), B::vf()
}
/*
B::vf()
A::f() A::vf()
A::foo() B::vf()
B::vf()
A::f() A::vf()
A::foo() B::vf()
*/
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]