-1

I am creating a small project in c++ with the concept of inheritance and std::vector. I want to add my different clients in std::vector of Parent Class but when I call the run method, it always calls the Parent class run method not the child class run method.

#include <vector>
#include <iostream>
class IClient
{
    public:
        void run(){std::cout<<"Base Client Called"<<std::endl;}

};

class AFKClient : public IClient
{
    public:
        void run() 
        {
            std::cout<<"AFK Client Called"<<std::endl;
            
        }
};

class Application
{
   public:
        std::vector<IClient> clients;
        void addClients(IClient client) 
        {
            clients.push_back(client);
        }

        void run() 
        {
            for (auto c: clients)
            {
                std::cout<<"calling client"<<std::endl;
                c.run();
            }
            
            
        }
};

int main()
{
    Application application;
    AFKClient afkClient;
    application.addClients(afkClient);
    application.run();
    return 0;

}

gul
  • 38
  • 6
  • well... try to read about `virtual` and you will know why https://stackoverflow.com/questions/2391679/why-do-we-need-virtual-functions-in-c – Alberto Sinigaglia Jul 10 '21 at 10:26
  • 1
    And even after you make `run` virtual, it still won't work due to [object slicing](https://en.wikipedia.org/wiki/Object_slicing). You need a container of (possibly smart) pointers to `IClient`, not `IClient` objects themselves. – Igor Tandetnik Jul 10 '21 at 14:50

1 Answers1

0

You'll need to change the definition of Application up a bit to support inheritance like you're expecting. Consider changing the vector to a vector of pointers:

std::vector<std::unique_ptr<IClient>> clients;

Then you'll need to change the addClients method as well:

void addClients(std::unique_ptr<IClient> client) 
{
    clients.push_back(std::move(client));
}

// then call it later on like:
application.addClients(std::make_unique<AFKClient>(afkClient));

This will actually call the virtual functions that you want. Generally anytime you're dealing with inheritance you'll need to store pointers to the base class rather than the base class itself.

mattlangford
  • 1,260
  • 1
  • 8
  • 12