Dear gurus,
I have been reading about polymorphism and generally think that I get the idea. At least I've gotten some code to work. Now I'm trying to get a little fancier and can't seem to figure out the following dilemma.
I have an abstract class Base, and some Derived classes:
Until recently, I was happy with just declaring a derived class and using it:
Now, what I really want is to be able to decide at runtime what class type to use. I can't pre-declare it either because I have pure virtual functions (e.g. f2) in my Base class. I tried making them non-pure (just empty) and then assigning like this:
It compiled fine, but the program clearly does not work right. So now I'm realizing that I'm missing some concepts here and need help.
Thanks in advance
I have been reading about polymorphism and generally think that I get the idea. At least I've gotten some code to work. Now I'm trying to get a little fancier and can't seem to figure out the following dilemma.
I have an abstract class Base, and some Derived classes:
Code:
class Base {
public:
void f1 () {
//....
}
virtual void f2() = 0;
};
class Derived1 {
public:
Derived1(int p1, int p2) {
//...
}
void f2() {
//...
}
};
class Derived2 {
public:
Derived2(int p1, int p2) {
//...
}
void f2() {
//...
}
};
Code:
void someFunc(Base var);
int main(int argc, char *argv[]) {
Derived var(p1, p2);
someFunc(var);
return 0;
}
Code:
void someFunc(Base var);
int main(int argc, char *argv[]) {
Base var;
if (arg[1] == 0) {
Derived1 v(p1, p2);
var = v;
} else {
Derived2 v(p1, p2);
var = v;
}
someFunc(var);
return 0;
}
Thanks in advance
Comment