updated code using std::string types rather than char*. string additionsconcatenations are possible now and I see what you originally meant by dynamic types.
// polymorphism test.cpp : Defines the entry point for the console application.
//
#include <iostream>
using std::cout;
using std::string;
class animal
{
protected:
string message;
public:
string name;
animal()
{
this->message = "Hello from ";
this->name = "SOMEANIMAL. I don't have a name yet :(";
cout << this->message + this->name + "\n";
}
virtualvoid eats() = 0;
virtual ~animal()
{
this->message = "Goodbye from ";
if (this->name == "SOMEANIMAL. I don't have a name yet :(")
{
this->name = "SOMEANIMAL. REALLY? NO ONE EVER GAVE ME A NAME!? :(";
}
cout << this->message + this->name + "\n";
}
};
class dog : public animal
{
public:
void eats()
{
this->message = "dog bones";
cout << this->name + " loves: " + this->message + "\n";
}
};
class cat : public animal
{
public:
void eats()
{
this->message = "cat food";
cout << this->name + " loves: " + this->message + "\n";
}
};
//a helper class which sets an animals name member
class animalNamer
{
public:
staticvoid setName(string param, animal *obj)
{
obj->name = param;
cout << "I have a name now! It is: " + obj->name + "\n";
}
};
int main()
{
//two animals created on the heap and their names set with the static helper
dog *Scooby = new dog;
animalNamer::setName("Scooby", Scooby);
cat *Garfield = new cat;
animalNamer::setName("Garfield", Garfield);
//eats is a pure virtual function which must be implemented in all derived animals
Scooby->eats();
Garfield->eats();
//clean up the heap
delete Scooby;
delete Garfield;
//an animal created on the stack
dog StackDog;
StackDog.eats();
return 0;
}
When you use the class initializer list, how do you know the type of message, or name, as you have written them? Or is that just explicitly defined in the declaration?
shouldn't it be:
1 2 3 4 5
animal::animal()
: string message("Hello from "), string name("SOMEANIMAL. I don't have a name yet :(")
{
cout << this->message + this->name + "\n";
}
Those 'message' and 'name' are members of the class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
class animal {
// member declarations
std::string message; // message is a string
std::string name; // name is a string
public:
animal() // default constructor
: message("Hello from "), name("SOMEANIMAL. I don't have a name yet :(")
{
cout << this->message + this->name + '\n';
}
animal( const std::string & name ) // another constructor
: message("Hello from "), name( name )
{
cout << this->message + this->name + '\n';
}
};