I want to understand the reason behind the output of the following C++ programs involving virtual functions. Please also explain how the function pointer table and virtual pointer table containing links to function pointer tables will be generated in the following 2 cases and how the call is resolved at runtime.
/******* PROGRAM 1 *******/
#include <iostream>
using namespace std;
class Car {
public:
virtual void foo() {
cout<<"Car"<<endl;
}
};
class Bmw: public Car {
public:
void foo1() {
cout<<"Bmw"<<endl;
}
};
int main() {
Car *c = new Bmw();
c->foo(); // gives output Car even though foo()
//function does not exist in BMS class.
return 0;
}
/******* PROGRAM 2 *******/
#include<iostream>
using namespace std;
class Car {
public:
virtual void foo() {
cout<<"Car"<<endl;
}
};
class Bmw: public Car {
public:
void foo() {
cout<<"Bmw"<<endl;
}
};
class Bmw7: public Bmw {
public:
void foo1(){
cout<<"Bmw7"<<endl;
}
};
int main() {
Car *c = new Bmw7();
c->foo(); //gives output Bmw. Why output is not Car ??
return 0;
}