Re: Enable Polymorphism on Run()
On Apr 30, 3:48 pm, Victor Bazarov <v.Abaza...@comAcast.net> wrote:
Immortal Nephi wrote:
I am trying to enable polymorphism. I created three derived c=
lasses
as B1, B2, and B3. class B1, B2, and B3 are derived from class A.
Only one virtual function Run() is invoked to select class B1, B2, or
B3 from class A.
I do not want to reassign reference of class B1, B2, and B3 to c=
lass
A pointer inside main() body. They can be done inside Run() body.
When you compile and run my source code, Run() is always invoked to
class B1 each time.
Please assist me to make the correction. Thanks for your advi=
ce.
#include <iostream>
class A
{
public:
A() : regA(0), regX(0), regY(0)
{
cout << "A()\n";
}
~A()
{
cout << "~A()\n";
}
void virtual Run(A* pa, A& ra)
If you are going to assign to 'pa' and hope to keep the change outside
of this function, 'pa' cannot be passed by value, otherwise the new
value (after assignment) only exists inside 'Run' function and the
caller does not know about it. Try printing the value of 'pa' in 'main=
'
right after each call to 'Run'...
Hi, V
You are correct about pass by value. I am unaware of A* is a
reference, but it should be A*&. Thanks for the tip. I have one
problem.
{
cout << "A::Run()\n";
}
/* OK */ pa->Run(pa, b2); // invoke B1:Run() & Reassign B2 to Run()
/* OK */ pa->Run(pa, b3); // invoke B2:Run() & Reassign B3 to Run()
/* NO */ pa->Run(pa, b1); // invoke B3:Run() & Reassign B1 to Run()
After you reassign b3 to pa, third function of pa->Run(pa, b1) above
will invoke to A::Run() instead of B3::Run(). Please give me a clue
what is going wrong?
Thanks...