Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple interfaces inhertience. Casting from one to another

Tags:

c++

Consider the following set of classes/Interfaces:

class IFish{
public:
virtual void eat() = 0;
}

class IFriendly{
public:
virtual void protect() = 0;
}

class IAggresive{
public:
virtual void attack(Point inDest) = 0;
}

class CDolphin : public IFish, IFriendly{
eat...
protect....
}

class CShark : public IFish, IAggresive{
eat....
attack...
}

Now I am having the following class

void CDiver
{

Void shouldRunAway(IFish* fish)
{
//???
}

}

My question is , can "shouldRunAway" extract from the fish argument whether it is an IAggresive or IFreindly (if it is any of these at all...) is there some kind of casting that can help out?

like image 926
user88637 Avatar asked Oct 23 '25 16:10

user88637


2 Answers

Expanding on what Drakosha posted, you would dynamic_cast the IFish pointer into an IAggressive pointer and check if it is NULL or not. Like this;

#include <iostream>

class IFish {
public:
    virtual void eat() = 0;
};

class IFriendly {
public:
    virtual void protect() = 0;
};

class IAggressive {
public:
    virtual void attack() = 0;
};

class Dolphin : public IFish, public IFriendly {
public:
    virtual void eat() {
        std::cout << "Dolphin::eat()\n";
    }

    virtual void protect() {
        std::cout << "Dolphin::protect()\n";
    }
};

class Shark : public IFish, public IAggressive {
public:
    virtual void eat() {
        std::cout << "Shark::eat()\n";
    }

    virtual void attack() {
        std::cout << "Shark::attack()\n";
    }
};

class Diver {
public:
    void shouldRunAway( IFish *fish ) {
        if ( dynamic_cast<IAggressive *>( fish ) != NULL ) {
            std::cout << "Run away!\n";
        } else {
            std::cout << "Don't run away.\n";
        }
    }
};

int main( int argc, char *argv[] ) {
    Dolphin dolphin;
    Shark shark;
    Diver diver;

    diver.shouldRunAway( &dolphin );
    diver.shouldRunAway( &shark );

    return 0;
}
like image 134
xian Avatar answered Oct 25 '25 04:10

xian


Take a look at dynamic_cast.

like image 41
Drakosha Avatar answered Oct 25 '25 04:10

Drakosha