What I\'m actually trying to do is cast a constructed moneypunct
to the punct_facet
in this question without writing a copy constructor as in this answ
It wouldn't work as you think, since you have made the function func
virtual. This means that even if you were to convert the pointer to Parent
to a pointer to Child
, the func()
of that object would still be Parent::func()
.
Now, you could theoretically do something like this:
#include
class Parent
{
public:
virtual void foo() { std::cout << "parent" << std::endl; }
};
class Child : public Parent
{
public:
virtual void foo() { std::cout << "child" << std::endl; }
};
int main()
{
Child child;
child.foo(); // "child"
child.Parent::foo(); // "parent"
Parent parent;
parent.foo(); // "parent"
((Child*)(&parent))->foo(); // still "parent"
((Child*)(&parent))->Child::foo(); // "child"
return 0;
}
And while i may receive some downvotes for posting this broken code, i think that it is necessary to show what is happening in this case. You would need to convert both, the pointer to the object, and then specify exactly which function you are intending to call.
Depending upon what you are doing, it may better be accomplished by using friend classes:
#include
class ParentHelper;
class ChildHelper;
class Parent
{
friend class ParentHelper;
friend class ChildHelper;
private:
int a=5;
};
class ParentHelper
{
public:
virtual void func(Parent *p)
{
std::cout << "parent helper, but i see a " << p->a << std::endl;
}
};
class ChildHelper : public ParentHelper
{
public:
virtual void func(Parent *p)
{
std::cout << "child helper, but i see a also " << p->a << std::endl;
}
};
void foo(Parent* p, ParentHelper *h)
{
h->func(p);
}
int main()
{
Parent p;
ParentHelper ph;
ChildHelper ch;
ph.func(&p);
ch.func(&p);
foo(&p, &ph);
foo(&p, &ch);
return 0;
}
Note several things: