0

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?

Keselme
  • 3,779
  • 7
  • 36
  • 68
  • 1
    [What did your book say?](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) This really isn't something to appeal to SO about. – StoryTeller - Unslander Monica Oct 31 '17 at 10:11
  • Possible duplicate of [Why do we need Virtual Functions in C++?](https://stackoverflow.com/questions/2391679/why-do-we-need-virtual-functions-in-c) –  Oct 31 '17 at 10:15

1 Answers1

2

Given your code, animal->talk() will always call Animal::talk(). Because animal is a Animal * and Animal::talk() is not virtual.

Now if you make Animal::talk() virtual, animal->talk() will call Dog::talk(). Normally this is done by looking at run-time at the vtable of animal to see the real type of the object and then call the most appropriate talk() function. But since you have Animal *animal = new Dog() just above, the compiler can choose to optimize the call by skipping the vtable lookup and make a direct call to Dog::talk() as the type is already known at compile time.

Benjamin T
  • 8,120
  • 20
  • 37