Krys
Krys

Reputation: 91

How to make a function in a base class that takes in a subclass of itself as a parameter?

Please forgive me if i'm missing some obvious thing - I am currently a pretty new to C++ and still learning it, thanks in advance.

So I have two functions, say, Base class ANIMAL, subclass SHEEP and subclass COW.

#include <iostream>

class Animal
{
public:
    void Noise(/*Subclass input here*/)
    {
        // Somehow call said subclass Noise() function
    }
};

class Sheep : public Animal
{
    void Noise()
    {
        std::cout << "Baa" << std::endl;
    }
};

class Cow : public Animal
{
    void Noise()
    {
        std::cout << "Moo" << std::endl;
    }
};

int main()
{
    Animal* animal = new Animal();
    Sheep* sheep = new Sheep();
    Cow* cow = new Cow();

    animal->Noise(/*Subclass input here, for example: sheep*/);

    return 0;
}

How would I input the subclass into the Base class then call the subclass function? I'm unsure whether this is even possible but worth a shot :)

Thank you in advance!

Upvotes: 3

Views: 121

Answers (1)

Constantinos Glynos
Constantinos Glynos

Reputation: 3186

Use virtual to utilize polymorphism and avoid having to pass the concrete object as an argument to the base class.

#include <iostream>

class Animal
{
    public:
        virtual void Noise() = 0;
};

class Sheep : public Animal
{
    public:
        void Noise() override
        {
            std::cout << "Baa" << std::endl;
        }
};

class Cow : public Animal
{
    public:
        void Noise() override
        {
            std::cout << "Moo" << std::endl;
        }
};

int main()
{
    Animal* animal = new Sheep();

    animal->Noise();

    delete animal;

    animal = new Cow();

    animal->Noise();

    delete animal;
}

The result is:

Baa
Moo

Example: https://rextester.com/TQK18582

As per comments bellow, this is a quick example that implements the above code using CRTP: https://rextester.com/TWMLD53466

Upvotes: 3

Related Questions