Calling a function of a class using templates

Viewed 57

I might be asking for something absurd here (and I am new with c++), but still I want to give it a try. I am trying to access a method of a class in a function that receives it's object, but, at the same time, I wanted to somehow not have to specify which class is that, that's why I am using templates. This sounds incredibly stupid, but anyway, that's the code:

class Dog;

class Animals{
public:
// initializes all protected variables
Animals(string fam, string gen, string espec, string subespec);
~Animals();

template <class A>
void Eat(A &);

protected:
    string family;
    string genre;
    string especies;
    string subespecies;
};

template <class A>
void Animals::Eat(A &obj)
{
    // this is where I don't know what I could do.
    std::cout << obj.methodOfA();
}

/---

int main()
{
    Dog *myDog = new Dog;
    myDog->Eat(myDog);

    //supposing I had class "Cats"
    Cat *myCat = new Cat;
    myCat->Eat(myCat);
}

This might be quite stupid, so feel free to point out my stupidity on the answers... if anyone ever answer this. I wanted this because I'll have many classes that are derived of class Animals, and independent of which of those classes, I wanted them to be able to use this method properly.

Thanks.

1 Answers
Related