I'm thinking that it could be a repeat question but I tried reading almost all the related posts and none of them were specific to what I'm looking for.
OK, So I understand that you cannot call a function in derived class from a base class pointer unless it is marked virtual. Like in reference program 1, it cannot call B class' WhichClass() if WhichClass() is not marked virtual.
#include<iostream>
using namespace std;
class A
{
public:
const char* WhichClass(){return "A";}
};
class B:public A
{
public:
const char* WhichClass(){return "B";}
};
int main()
{
B b;
A &a = b;
cout<<"In class "<<a.WhichClass();
return 0;
}
If I mark it as virtual then it calls the function of the most derived class from the base class. Now suppose if I add another class C inheriting from B (as shown in program 2), and if WhichClass() is not marked as virtual in the class B, then how can base reference (&a) call WhichClass() function in Class C? Also with class B reference (&b), how can it call WhichClass() in C when it is not even marked as virtual in class B as per what we observed in program 1?
#include<iostream>
using namespace std;
class A
{
public:
virtual const char* WhichClass(){return "A";}
};
class B:public A
{
public:
const char* WhichClass(){return "B";}
};
class C:public B
{
public:
const char* WhichClass() { return "C";}
};
int main()
{
C c;
A &a = c;
B &b = c;
cout<<"In class " << a.WhichClass() << endl;
cout<<"In class " << b.WhichClass() << endl;
return 0;
}
Because when you make a method a virtual in base class and create a base class pointer point to any derived class, then in that case it calls the most derived class function. In your case you have,
A &a = c;
here a pointer of base class A is pointing to class C, so when you call the WhichClass() method then method of class C is called.
B &b = c;
even here also when you call a function using base class pointer, the function of most derived class is called based on which class you are pointing. In this case pointer of class B is pointing to object of class C, so WhichClass() method of class C will be called. For more details, please check this,polymorphism