Re: Enable Polymorphism on Run()
On 30 Apr, 21:19, Immortal Nephi <Immortal_Ne...@hotmail.com> wrote:
I am trying to enable polymorphism. I created three de=
rived classes
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 class
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 yo=
ur advice.
You'll probably kick yourself...
#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)
{
cout << "A::Run()\n";
}
protected:
int regA;
int regX;
int regY;
};
class B1 : public A
{
public:
B1() : A()
{
cout << "B1()\n";
}
~B1()
{
cout << "~B1()\n";
}
void virtual Run(A* pa, A& ra)
{
cout << "B1::Run()\n";
pa = &ra;
Here's your problem. pa is passed by value, so changing the value of
pa in this function doesn't change the value in the calling function.
I think what you want is to replace "void virtual Run(A* pa, A& ra)"
with "void virtual Run(A*& pa, A& ra)" all through your code. Passing
by reference means that the line just above will change the variable
in the calling routine as well.
(If this doesn't make sense to you, I suggest reading question 4.8 of
the C FAQ, at http://c-faq.com/ptrs/passptrinit.html But using C++
gives you more ways to deal with the problem.)
Hope that helps.
Paul.