I have a question about the compiler behavior when I use up-casting in C++. For example I have this simple code:
class Animal {
public:
Animal() {}
void talk() {
std::cout << "I am an animal" << std::endl;
}
};
class Dog :public Animal {
public:
Dog(){}
void talk() {
std::cout << "I am a dog" << std::endl;
}
void eat() {
std::cout << "eating" << std::endl;
}
};
int main()
{
Animal* animal = new Dog();
animal->talk();//Output is "I am an animal"
//animal->eat();//Compilation error.
return 0;
}
My question is, where does the compiler go first when I run this? Does it look for the methods in Animal class, and then because I didn't use virtual it calls for the Animal's talk() method, or does it checks if the method exists in the Dog class first, and calls for the Animal's method?