Reputation: 5235
I want to inherit a class named CSprite from another class named CDocument before the CDocument actually declared, as some members of CDocument class are actually CSprite. I hope it don't seems confusing? Here is my code:
class CSprite: public CDocument {}
class CDocument
{
public:
CDocument();
~CDocument();
CSprite * AddSprite(string Name);
CSprite * GetSprite(string Name);
};
I'm getting "base class undefined" error. I'm wondering may be this is not possible at all. Is it? The reason I'm doing this is increasing my code readability. Every document can have many sprites. Sprites are documents actually which can have other sprites inside them.
Upvotes: 1
Views: 219
Reputation: 69988
Inheritance from an incomplete type is not possible.
You can solve the problem in following different ways:
template
in similar fashion as
CRTPUpvotes: 3
Reputation: 64223
No, that is not possible. The base class needs to be fully known, before defining derived class.
That looks like a broken design. You can fix by declaring CDocument first, and changing signatures :
class CDocument
{
public:
CDocument();
~CDocument();
CDocument * AddSprite(string Name);
CDocument * GetSprite(string Name);
};
class CSprite: public CDocument {}
Upvotes: 2
Reputation: 66
As CDocument.AddSprite/GetSprite both return a CSprite pointer, you may only need to declare the existence of CSprite in the document.
//declare CSprite
class CSprite;
class CDocument
{
public:
CDocument();
~CDocument();
CSprite * AddSprite(string Name);
CSprite * GetSprite(string Name);
};
You can define CSprite Later in this file or in another, at which point you should be able to inherit CDocument. Although if run into more problems, you may want to redesign the object structure.
//CSprite Class
class CSprite : public CDocument
{
...
};
Upvotes: 3
Reputation: 60255
Template the base:
class Document;
template<class Document=Document> class Sprite_t : public Document { };
typedef Sprite_t<Document> Sprite;
class Document { /* etc. */};
Upvotes: 2