Inheritance Problem

Started by
4 comments, last by Anima 19 years, 9 months ago
I hope someone can help with this, but its kinda difficult for me to explain. I've been messing around with inheritance, but have come across a problem. I have a base class with contains the following function:

eCWresult cCompressor::Compress_Init2 (const int iPercentage)
{
	float fRatio = (iPercentage / 100.0f);
	int iLevel = GetMinLevel () + (int)((GetMaxLevel () - GetMinLevel ()) * fRatio);

	return Compress_Init (iLevel);
}
The GetMinLevel and GetMaxLevel function are members of this base class. The problem is that when I derive a new class from this base class and replace the GetMinLevel and GetMaxLevel functions, it is still the original functions that are called when I call the Compress_Init2 function. The only way I've found to make it behave correct is to redefine the Compress_Init2 function in the derived class (even though it still has the same body) Is there a better way? (... I hope I explained that well enough.)
Advertisement
Are GetMinLevel and GetMaxLevel virtual in the base class? They need to be.
It's only funny 'till someone gets hurt.And then it's just hilarious.Unless it's you.
Yes, both GetMinLevel and GetMaxLevel are defined as virtual in the base class.
It could be this is supposed to happen - or it could be just the compiler (the accursed VC++ 6.0) and one of its many bugs.

Has anyone got any idea what the problem could be? Or have I just got the inheritance model messed up?
While MSVC 6 is fairly eccentric, chaces are it's not at fault here. Try posting a minimal but complete code sample that demonstrates your issue.
Well, whilst writing a 'trimmed down' code example of the problem I found out what the problem is - I'd simply forgot to make the derived function 'constant'.

The following code shows where I went wrong if anyone is interested:
#include <iostream>class cBase{public:	virtual int GetMinLevel () const { return 0; };	virtual int GetMaxLevel () const { return 9; };	virtual int Range () { return GetMaxLevel () - GetMinLevel (); };};class cDerived : public cBase{	int GetMinLevel () { return 0; }; // *	int GetMaxLevel () { return 4; }; // *};int main (){	cDerived test;	std::cout << test.Range () <<  endl;	return 1;}

The program will output 9 rather than 4 because I hadn't made the marked (*) functions constant.

It's something else learned, anyway!

This topic is closed to new replies.

Advertisement