'Saving a Child class instance in a parent type variable and using the Child's functions through parent variable?

I have two classes called Bird and Eagle. The Eagle is inherits from the bird. Now, I can use the Bird Class to store an eagle type instance. However, when i try to call the function of eagle using the variable a I get an error saying

error: ‘class bird’ has no member named ‘attack’

How do i use the function attack ? Also, will it be the similar for typescript?

#include <stdio.h>

class bird{
    public:
    void fly(){
        printf("fly");
    }
};

class eagle: public bird{
    public:
    void attack(){
        printf("attack");
    }
};

int main()
{
    bird *a = new eagle();
    a->attack();



    return 0;
}


Solution 1:[1]

The variable a is pointer to an object of type bird, so you're only allowed to call methods that are defined on the bird class. This makes sense - you can't treat all birds as eagles, after all.

You have a few options:

  1. Don't call non-bird methods
  2. Change the type of a to eagle*
  3. Use dynamic_cast to hack around the issue (not recommended, this is usually a sign that you've modeled your data incorrectly)
dynamic_cast<eagle*>(a)->attack();

Documentation for dynamic_cast: https://en.cppreference.com/w/cpp/language/dynamic_cast

Solution 2:[2]

You can create virtual function attack in bird, which does nothing.

Then attack definition in eagle will override the base one.

virtual void attack() = 0;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mackorone
Solution 2 Valentine Pupkin