My question is as follows:
I want (if it is possible) to "implement" virtual functions without using the "virtual" keyword (out of curiosity - I know the trick with functions pointers in C , I wish to do that in C++ !!). My "idea" is to have a flag which will be assigned in the constructor in order to indicate which instance this object is. My questions are: 1)Is it even possible ? 2)If so - what am I doing wrong ? or what is missing ?
I am using g++ which gives me these errors:
#‘B’ has not been declared
#‘C’ has not been declared
#class ‘B’ does not have any field named ‘flag’
#class ‘C’ does not have any field named ‘flag’
This is My suggestion:
#include <iostream>
using namespace std;
class A {
protected:
short flag;
public:
A(int f = 1) : flag(f) {}
void foo()
{
switch (this->flag)
{
case 1: cout << "A " << endl; break;
case 2: B :: foo(); break;
case 3: C :: foo(); break;
}
}
};
class B : public A{
public:
B(int f = 2) : A(f) {}
void foo() {cout << "B " << endl;}
};
class C : public B{
public:
C(int f = 3) : B(f) {}
void foo() {cout << "C " << endl;}
};
int main()
{
A a;
B b;
C c;
A *pb = &b;
A *pc = &c;
a.foo();
pb->foo();
pc->foo();
return 0;
} // end main
Thanks allot (!!) in advance , Guy.