"Joseph Cook" <jo******@mail.com> wrote in message
news:b6**************************@posting.google.c om...
I was wondering if there was any way to do the following:
If I have a class Base, and multiple Derived classes which all have
some different behavior on some function foo()...is there any good way
to have an object that can switch between these various
functionalities..using a pointer to the generic class?
as follows:
class Status
{
Status(){}
Base *mode;
Derived1 derived1;
Derived2 derived2;
};
class Base
{
virtual foo();
};
class Derived1 : public Base
{
foo(){cout<<"One";}
};
class Derived2 : public Base
{
foo(){cout<<"Two";}
};
Such that I can change *mode so that I can call mode->foo(), and can
expect to be able to choose whether mode->foo() is calling Derived1's
foo, or Derived2's foo. Is there any way to create such behavior?
Thanks!
Your example does not seem to match what you've stated that you want.
In your example, you have three separate objects: one is of the base type,
the others are of the other two derived types. In the example, you could
just call derived1->foo() or derived2->foo(), based on whatever condition
you chose. The mode pointer isn't even needed, unless you also want to call
the Base class' foo function (via mode->foo()).
But, from your comments, it seems like you don't want three objects, but
rather a single object that can act as any of the derived classes. If you
actualy want to change an existing Base object from behaving like a Derived1
object to behaving like a Derived2 object, that's not (generally speaking)
possible, because Derived1 and Derived2 are not related.
However, you can create an instance of a Derived1 class and assign it to a
pointer-to-Base class variable (a Base*), and it will then behave as a
Derived1 object. (but you'll want to be sure that the Base class destructor
and the foo() function are both virtual). Then you can delete that
instance, and create a new one based on Derived2 and it will behave as a
Derived2 object.
Like this:
Base* mode = new Derived1();
mode->foo(); // calls Derived1::foo
delete mode;
mode = new Derived2();
mode->foo(); // calls Derived2::foo
delete mode;
But you can't create an object of type Derived1 and "switch it" to behave
like a Derived2 object. There's simply no mechanism for that which is safe
and reliable. Casting is "possible", but it is not guaranteed to work. For
example:
Base* mode = new Base();
(Derived1*)mode->foo();
(Derived2*)mode->foo();
This may work. It may blow up horrendously. And, it may work for you but
fail for others! You just can't say for sure, because you have not created
instances of Derived1 and Derived2...you are just lying to the compiler and
telling it that you have!
-Howard