-5

I want to implement a template like this,

class animal{
}
class beast : public animal {
public:
beast(string name){}
void cry(){
cout<<"kuuuuu"<<endl;
}
}
int main(){
vector<animal*> a;
a.push_back(beast("tiger"))
vector[0].cry();
}

I want to implement similar to it. But my visualstudio cannot find the cry() function.

Please, how can I do it?

3 Answers3

4

animal does not have a cry method. So you cannot call a cry on animal.

Also you have numerous syntax errors, which should give you errors before this line:

Your vector contains pointers and you are trying to stuff object itself inside.

To access member of object pointer points to, you should use ->, not ..

Revolver_Ocelot
  • 8,609
  • 3
  • 30
  • 48
1

A lot of changes needed.static_cast is essential to call your cry method.

  1. class definition should end with ;

  2. Since you created vector<animal*>, you need to new the object before push back.

  3. When you invoke the function cry , you need to static_cast it back to beast* and use -> instead . to invoke the cry function.

class animal{

};
class beast : public animal {
public:
 beast(std::string name){}
void cry(){
std::cout<<"kuuuuu"<<std::endl;
}
};
int main(){
std::vector<animal*> a;
a.push_back(new beast("tiger"));
(static_cast<beast*>(a[0]))->cry();
}
Steephen
  • 14,645
  • 7
  • 40
  • 47
1
#include <vector>
#include <iostream>
#include <string>

using namespace std;

class animal {
public:
    virtual void cry() = 0; // declare public virtual cry method
};

class beast : public animal {
public:

    beast(string name) {
    }

    void cry() {
        cout << "kuuuuu" << endl;
    }
};

int main() {
    vector<animal*> a;
    a.push_back(new beast("tiger")); // create new object and end with semicolon
    a[0]->cry(); // use -> instead of . to call cry method of beast object pointed at
}
Ely
  • 10,860
  • 4
  • 43
  • 64