Sign in to follow this  
Anima

Inheritance Problem

Recommended Posts

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

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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!

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this