I'm trying to implement my java assignment (it's working in java) to C++ but when I tried to inherit from the Animal class, Crocodile class' constructor says "class 'Crocodile' does not have any field named 'name'". How can I fix this problem. I saw that they're using templates but I don't understand the point.
#include <iostream>
#include <string>
class Animal {
private:
std::string name { "Unknown Name" };
public:
virtual std::string walk() const = 0;
virtual std::string fly() const = 0;
virtual std::string swim() const = 0;
virtual std::string hunt() const = 0;
virtual std::string type() const = 0;
std::string getName() const {
return name;
}
void setName(const std::string& nam) {
name = nam;
}
Animal() {}
Animal(const std::string& nam) : name { nam } {}
virtual ~Animal() {}
};
class Crocodile : public Animal {
public:
using Animal::Animal;
std::string type() const override {
return"Crocodile";
}
std::string swim() const override {
return" swims fast in water.";
}
std::string walk() const override {
return" walks slow on land.";
}
std::string hunt() const override {
return" hunts on land and in water.";
}
std::string fly() const override {
return" cannot fly.";
}
};
class Tiger : public Animal {
public:
using Animal::Animal;
std::string type() const override {
return"Tiger";
}
std::string swim() const override {
return" swims good in water.";
}
std::string walk() const override {
return" runs fast on land.";
}
std::string hunt() const override {
return" hunts on land and in water.";
}
std::string fly() const override {
return" cannot fly.";
}
};
void display(const Animal& an) {
std::cout << "For " << an.getName() << '\n';
std::cout << " is a " << an.type() << '\n';
std::cout << an.fly() << '\n';
std::cout << an.swim() << '\n';
std::cout << an.walk() << '\n';
std::cout << an.hunt() << '\n';
}
int main() {
constauto c { Crocodile("ticktock") };
constauto t { Tiger("tigger") };
display(c);
display(t);
}
which displays:
For ticktock
is a Crocodile
cannot fly.
swims fast in water.
walks slow on land.
hunts on land and in water.
For tigger
is a Tiger
cannot fly.
swims good in water.
runs fast on land.
hunts on land and in water.