bman
bman

Reputation: 5235

Inherit class b from class a before class a declare

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

Answers (4)

iammilind
iammilind

Reputation: 69988

Inheritance from an incomplete type is not possible.
You can solve the problem in following different ways:

  1. Change the design where the dependency is where derived class depends on base class
  2. Have pointer or reference of derived class inside base class with derived class being forward declared
  3. Make the base class a template in similar fashion as CRTP

Upvotes: 3

BЈовић
BЈовић

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

jfox
jfox

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

jthill
jthill

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

Related Questions