I have recently learned about virtual functions and it is to my understanding that they are a keyword that goes in front of the return type when defining a function. They go in a base class, and make it so that if a member function of the base class is called with a base class type object, say b.display(), then the compiler will look in any derived classes for a definition of the function display() and if it fails to then just uses the base classes version of the function. This is what my textbook told me. However when I tested this out with this program it returned results that did not match my understanding. Here is the program:
Base_derived.h:
#include<iostream>
using namespace std;
class base
{
public:
virtual int get_tag()
{return 1;}
};
class derived: public base{
public:
int get_tag()
{return 2;}
};
main.cpp:
#include"derived.h"
#include<iostream>
using namespace std;
int main()
{
class derived d;
cout<<"d.get_tag():"<<d.get_tag()<<endl;
class base b;
cout<<"b.get_tag():"<<b.get_tag()<<endl;
system("pause");
return 0;
}
When the program ran it outputted:
"d.get_tag():2
b.get_tag():1"
I thought that b.get_tag() would return 2 because it is a virtual function. Thanks for any help.