Search code examples
c++pointersderived-class

More simple way to access derived properties & methods given base pointer


Right now, I have this code, and it is working as expected. In order to set properties of object type Cannon when given the base type Defense*, I am casting Cannon* to it and using that to set the properties.

void fillProperties(Defense* defense)
{
    if (defense->getType() == "Cannon")
    {
        Cannon* c = (Cannon*)defense;
        double cannonBallDamage, cannonBallSpeed, blastRadius;

        cout << "Cannon ball damage (hp): ";
        cin >> cannonBallDamage;
        cout << "Cannon ball speed (ft/sec): ";
        cin >> cannonBallSpeed;
        cout << "Blast radius (ft): ";
        cin >> blastRadius;

        c->setBlastRadius(blastRadius);
        c->setCannonBallDamage(cannonBallDamage);
        c->setCannonBallSpeed(cannonBallSpeed);
    }
}

The setBlastRadius, setCannonBallDamage, and setCannonBallSpeed methods exist only inside Cannon, not in Defense. I have 6 different types of classes that derive from Defense with their own extra properties, Cannon being one.

My question is: is there a more simple way than checking the type of the object and creating a new (casted) pointer for each one to set its properties?


Solution

  • You can add virtual method in Defense:

    class Defense
    {
    public:
        virtual ~Defense()
        virtual void fillProperties() = 0;
        // [...]
    };
    
    class Canon : public Defense
    {
    public:
        virtual void fillProperties() override
        {
            cout << "Cannon ball damage (hp): ";
            cin >> this->cannonBallDamage;
            cout << "Cannon ball speed (ft/sec): ";
            cin >> this->cannonBallSpeed;
            cout << "Blast radius (ft): ";
            cin >> this->blastRadius;
        }
        // [...]
    
    private:
        double cannonBallDamage, cannonBallSpeed, blastRadius;
    };
    

    Visitor pattern can be used to avoid to add too many methods in Defense