• Popular Now

• 9
• 13
• 18
• 19
• 27

Archived

This topic is now archived and is closed to further replies.

inheritance

This topic is 5841 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

How do i return a class of an inherited class, from within a base class? (in the code below, how can i make GetFraction() to compile)? Right now, it doesnt recognize the return type (CFraction) as a valid type, since the class is defined below it. What is a way around this?


class CNumber : public CElement
{
public:
virtual CFraction GetFraction() = 0;

// ... Rest of class truncated .... //

};

class CFraction : public CNumber
{
public:
int	Numerator;
int	Denominator;

// .... Rest of class truncated .... //

};


Share on other sites
I''m not home right now so I can''t test this out, but try to just declare your class like

class CFraction;

before the function which returns the type, then give the full declaration later on after the base class is declared.

If that doesn''t work you can always dynamically allocate the CFraction and then return a pointer to it, though that''s a little bit ify because you''re relying on the user to explicitly call delete.

--------------------
Matthew Calabrese
Realtime 3D Orchestra:
Programmer, Composer,
and 3D Artist/Animator
"I can see the music..."

Share on other sites
You might want to consider changing it to return a CNumber instead since your base class shouldn''t require knowledge of its diriving classes.

More likely, however, you shouldn''t have GetFraction in CNumber. Is CFraction the only class that inherits from CNumber? If not what happens in the implemenation of GetFraction in those other classes? If yes they should be combined into one class.

Share on other sites
Yeah, what''s probably better is to just make constructor for CFraction that has one parameter -- a CNumber.

Then, you can get pretty much the same effect of calling "GetFraction()" by just creating an instance of the derived class and passing a CNumber object to the constructor.

--------------------
Matthew Calabrese
Realtime 3D Orchestra:
Programmer, Composer,
and 3D Artist/Animator
"I can see the music..."