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.

Recommended Answers

All 2 Replies

>>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.

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?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.