This is work through sample of my class. To be honest, I know how the virtual works with the dynamic memory. But this is pretty hard to understand for me how this workthrough works. Can you guys please let me know how it works? In the case it is calling a.display(); foo(a);, I understand but I cannot understand how it calls function in horse when it calls animal function when it directly calls function in the horse.So I want general overview of this code, and since both are not that long, it won't take too long. This is header.
// Virtual Functions
// Animal.h
#include <iostream>
class Animal{
public:
virtual void display() const;
};
class Horse : public Animal {
public:
void display() const;
};
This is implementation file.
// Virtual Functions
// Animal.cpp
#include "Animal.h"
void Animal::display() const {
std::cout << "Animal" << std::endl;
}
void Horse::display() const{
std::cout << "Horse" << std::endl;
}
and this is the first version.
// Virtual Functions - Monomorphic
// h16.m.cpp
#include "Animal.h"
void foo(const Animal a){
a.display();
}
void goo(const Animal& a){
a.display();
}
int main(){
Animal a;
Horse h;
a.display();
foo(a);
goo(a);
h.display();
foo(h);
goo(h);
}
and this is the second one.
// Virtual functions - Polymorphic
// h16.cpp
#include "Animal.h"
void foo(Animal a){
a.display();
}
void goo(Animal& a){
a.display();
}
void foogoo(Animal& a){
a.Animal::display();
}
int main(){
Animal* a; // Static typing
a = new Animal(); // Dynamic typing
a->display(); // ani
foo(*a); //ani
goo(*a); //ani
delete a;
a = new Horse(); // Dynamic typing
a->display(); //horse
foo(*a); //ani
goo(*a); //ani
foogoo(*a); //ani
delete a;
}