Reputation: 11
I am wondering how can I dynamically call class functions. Let's say I have a class '"dog", which contains function getname(), that returns name of that specific animal. But how could I call function dog::getname() like that but without the "dog" at the beginning I would use std::string animal = "dog", and then somehow do like animal::getname()
I haven't tried anything yet, because I simply have no idea how I could get similar result, or if it's even possible.
class dog {
public:
static std::string getname() {
return "Something";
}
}
class cat {
public:
static std::string getname() {
return "Something2";
}
}
std::string animal = "dog";
And now somehow call the function getname related to the animal which is in the string.
Upvotes: 0
Views: 1268
Reputation: 5331
Are you looking for polymorphism?
#include <memory>
#include <string>
// An animal interface for all animals to implement
class Animal {
public:
virtual ~Animal() = default;
virtual std::string getName() const = 0;
};
// An implementation of the animal interface for dogs
class Dog final : public Animal {
public:
std::string getName() const override {
return "John";
}
};
// An implementation of the animal interface for cats
class Cat final : public Animal {
public:
std::string getName() const override {
return "Angelina";
}
};
int main() {
std::unique_ptr<Animal> animal0 = std::make_unique<Dog>();
std::unique_ptr<Animal> animal1 = std::make_unique<Cat>();
// You can pass around a std::unique_ptr<Animal> or Animal *
// just as you would pass around a string.
// Although, std::unique_ptr is move-only
std::cout << animal0->getName() << '\n';
std::cout << animal1->getName() << '\n';
}
Upvotes: 1
Reputation: 32063
C++ itself doesn't provide reflection, which would let you do this easily -- the class names are stripped away during compilation.
If you really want to call different functions based on a string name, you'd have to store the mapping from the names to the function pointers and use it to invoke the function you want.
Depending on your specific use-case you could do this by hand (see Using a STL map of function pointers) or use more sophisticated solutions from the thread someone already linked to: How can I add reflection to a C++ application?
Upvotes: 0