I have a class A
as a base class of class B
.
I have called the non-virtual function, abc()
, within my virtual function, xyz()
, as mentioned below.
Due to run-time polymorphism, B:xyz
is called – I understand this.
However, I don't understand, why was it followed by B:abc
and not A:abc
, as abc
is a non-virtual function.
Please note: I have come across the following question: Virtual function calling a non-virtual function. It mentions that calling abc()
within the virtual function is equivalent to this->abc()
, hence the output. However, I am not sure I understand this part.
Because, when I do the opposite (i.e. a non-virtual function calling a virtual function), that time correct run time polymorphism is displayed. What happens to the this pointer then?
//Virtual function calling non-virtual
class A
{
public:
void abc()
{
cout<<"A:abc"<<endl;
}
virtual void xyz()
{
cout<<"A:xyz"<<endl;
abc();
}
};
class B: public A
{
public:
void abc()
{
cout<<"B:abc"<<endl;
}
void xyz()
{
cout<<"B:xyz"<<endl;
abc();
}
};
int main() {
A *obj3 = new B;
obj3->xyz();\
return 0;
}
Output
B:xyz
B:abc
//Non-virtual calling virtual function
#include <iostream>
using namespace std;
class A
{
public:
void abc()
{
cout<<"A:abc"<<endl;
xyz();
}
virtual void xyz()
{
cout<<"A:xyz"<<endl;
}
};
class B: public A
{
public:
void abc()
{
cout<<"B:abc"<<endl;
xyz();
}
void xyz()
{
cout<<"B:xyz"<<endl;
}
};
int main() {
A *obj3 = new B;
obj3->abc();
return 0;
}
Output
A:abc
B:xyz