Link to home
Start Free TrialLog in
Avatar of Wisnu
WisnuFlag for Indonesia

asked on

[ASK] Why can't I override the Base Class method?

Hi Experts,

I have a base class that has a virtual method named Call as follow:
template<typename A, typename B>
class BaseFunc
{
public:
	virtual B Call(A in1)
	{
		B b;
		return b;
	}
};

Open in new window


Then I create a new class derived from the base class as follow:
class AnimalName :
	public BaseFunc<Animal, std::string>
{
public:
	virtual std::string Call(
		const std::shared_ptr<Animal> &customer);
};

Open in new window


The class Animal is created in two files; Animal.h and Animal.cpp. The Animal.h file content is as follow:
class Animal
{
public:
	static std::vector<Animal> animals;
	int id = 0;
	std::string name = "";

	Animal();

	static std::vector<std::string> GetAnimalNames();

	template<typename T>
	static std::vector<T> GetAnimalByFunction(
		const std::shared_ptr<BaseFunc<Animal, T>> &funct);
};

Open in new window


And the Animal.cpp file content is as follow:
#include "Animal.h"

using namespace std;

vector<Animal> Animal::animals;

Animal::Animal()
{
}

string AnimalName::Call(
	const shared_ptr<Animal> &animal)
{
	return animal->name;
}

vector<string> Animal::GetAnimalNames()
{
	return Animal::GetAnimalByFunction<string>(
		make_shared<AnimalName>());
}

template<typename T>
vector<T> Animal::GetAnimalByFunction(
	const shared_ptr<BaseFunc<Animal, T>> &funct)
{
	vector<T> returnList;
	for (auto customer : Animal::animals)
	{
		returnList.push_back(
			funct->Call(customer));
	}
	return returnList;
}

Open in new window


Now, I  have a main.cpp file as follow:
#include <iostream>
#include "Animal.h"

using namespace std;

void SetAnimals()
{
	int i = 0;

	vector<string> animalNames;
	animalNames = {
		"Peanut",
		"Coco",
		"Rocky",
		"Harley",
		"Pepper",
		"Roxy"
	};

	for (auto name : animalNames)
	{
		Animal a;
		a.id = i++;
		a.name = name;
		Animal::animals.push_back(a);
	}
}

int main()
{
	Animal a;

	SetAnimals();

	cout << "Animal names:" << endl;
	vector<string> animals =
		a.GetAnimalNames();
	for (auto name : animals)
	{
		cout << name << endl;
	}

	return 0;
}

Open in new window


When I run the code, I get no animal names since the Call() method is invoked from the base class (BaseFunc) instead of the derived class (AnimalName).

The following is my console snapshot:User generated image
How can I override the Call method in BaseFunc class?
override.zip
SOLUTION
Avatar of phoffric
phoffric

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Wisnu

ASKER

Many thanks, Experts :)