0

Hello I have been trying to understand virtual functions for a while and when I made a program to demonstrate the use of virtual functions it didn't and someone gave me this piece of code that would demonstrate the proper way to utilize a virtual function:

#include"derived.h"
#include<iostream>
using namespace std;
int main()
{

class derived d;
cout<<"d.get_tag():"<<d.get_tag()<<endl;
class base& b= d;
cout<<"b.get_tag():"<<b.get_tag()<<endl;
system("pause");
return 0;
}

Which went with the derived.h:

class base
{
public:
	virtual int get_tag()
	{return 1;}
protected:
};
class derived: public base{
public:
	int get_tag()
	{return 2;}
};

I know that the person's example uses the virtual function correctly but I haven't the faintest clue what class base& b= d; means. Does it read "make a class base type object that is a reference to class d"? Thanks for any help.

2
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by CPPRULZ
0

>>but I haven't the faintest clue what class base& b= d; means

It means b is a reference to d -- in otherwords both b and d are two different names for the same object.

0

Ohh okay, but b is a base class reference to d so without the virtual keyword in front of base's int get_tag() why doesn't it call the derived version?

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.