What if virtual functions in both base classes have the same name?


If virtual functions in both base classes have the same name, the sub classe cannot implement separate functions for the two base classes, while C# has no this problem.

enum { EBASE1, EBASE2, EBASE3, EBASE4 };
struct CMultiBase1
{
	virtual int f()
	{
		return EBASE1;
	};
};
struct CMultiBase2
{
	virtual int f()
	{
		return EBASE2;
	};
};

struct CMultiSub: CMultiBase1, CMultiBase2
{
	int f() //cannot to say to overrides f() for CMultiBase1 or CMultiBase2.
	{       //but with C#, CBase1 or CBase2 can be indicated explicitly
		return EBASE3;
	};
};
void TestMulti()
{
	CMultiSub s;
	CMultiBase1 *p1 = &s;
	CMultiBase2 *p2 = &s;
	_ASSERT(p1->f() == EBASE3);
	_ASSERT(p2->f() == EBASE3);
}

However, C#’s answer for this problem seems redundant, because this problem can be solved by adding another layer.
We replace CMultiSub and TestMulti() above with the following code to solve the problem.

struct CMultiBase1a: CMultiBase1
{
	int f()
	{
		return f1a();
	};
	virtual int f1a() = 0;
};
struct CMultiBase2a: CMultiBase2
{
	int f()
	{
		return f2a();
	};
	virtual int f2a() = 0;
};
struct CMultiSub: CMultiBase1a, CMultiBase2a
{
	int f1a()
	{
		return EBASE4; //for CMultiBase1
	};
	int f2a()
	{
		return EBASE5;  //for CMultiBase2
	};
};
void TestMulti()
{
	CMultiSub s;
	CMultiBase1 *p1 = &s;
	CMultiBase2 *p2 = &s;
	_ASSERT(p1->f() == EBASE4); //for CMultiBase1
	_ASSERT(p2->f() == EBASE5); //for CMultiBase2
}

By adding another layer, CMultiBase1a and CMultiBase2a, we can differentiate the two f() in CMultiBase1 and CMultiBase2.

Advertisements
Comments are closed.
%d bloggers like this: