Re: Does object have function?
On 29 Oct, 01:21, Rui Maciel <rui.mac...@gmail.com> wrote:
Jim Langston wrote:
What I am trying to accomplish: I have a map of polymorphic objects and
these objects may have certain methods defined or not. If the instan=
ce
has the method then I want to call it, otherwise not.
It is trivial to create a virtual function for a few functions. But =
I
would have to add every single function that could be interfaced.
I would just to somehow be able to tell if an instance has a function
available. Consider:
It would be much easier to do something like:
<code>
class Base {
public:
virtual void foo() { //do nothing}
};
class DerivedOne : public Base {
public:
void foo() { //do something }
};
class DerivedTwo : public Base {
public:
void foo() { //do something}
};
class DerivedThree: public Base {
};
int main(void) {
Base* bps[3];
bps[0] = new DerivedOne();
bps[1] = new DerivedTwo();
bps[2] = new DerivedThree();
for ( auto i = 0; i < 3; ++i )
{
thisOne->foo();
}
return 0;}
</code>
I'm not an expert but I'd recommend this technique as well. Just one
thing to add - if you find yourself adding the same "foo" function to
more than one derived class, consider whether you could introduce it
in a single class and derive the others from it.
Just my two pence...
Paul.