I have an abstract class that has a variable owner_
that is a string. Each derived class declares the name of this variable. Is it better practice to have the variable in the abstract base class, or can I better implement it multiple times in the derived class?
#include <string>
#include <iostream>
class Pet
{
public:
Pet(const std::string& owner) : owner_(owner) {}
virtual ~Pet() = 0;
virtual void print_status() = 0;
protected:
const std::string owner_;
};
Pet::~Pet() {}
class Dog : public Pet
{
public:
Dog(const std::string& owner) : Pet(owner) {}
~Dog() {};
void print_status()
{
std::string s = "Woof! My owner is ";
s += owner_;
std::cout << s << std::endl;
}
// Or better here?
// private:
// const std::string owner_;
};
class Cat : public Pet
{
public:
Cat(const std::string& owner) : Pet(owner) {}
~Cat() {};
void print_status()
{
std::string s = "Meow! My owner is ";
s += owner_;
std::cout << s << std::endl;
}
// Or better here?
// private:
// const std::string owner_;
};
int main()
{
Dog dog("Mario");
dog.print_status();
Cat cat("Luigi");
cat.print_status();
return 0;
}