0

I am relatively new to C++, and I am trying to write a simple 2D engine. However, there is a problem with the current structure which was okay in other languages (AS3 etc). I have two classes, one called DisplayObject, and another one called DisplayObjectContainer. DisplayObjectContainer is a subclass of DisplayObject, but DisplayObject has a pointer to a DisplayObjectContainer parent as property. I can't figure out a way to properly include each other in their files. I can't forward declare DisplayObjectContainer in DisplayObject because I need to access DisplayObjectContainer's methods in DisplayObject.

DisplayObject:

class DisplayObject
{
    public:

        DisplayObjectContainer *parent;
...
    ...this->parent->globalTransform...
...

DisplayObjectContainer:

class DisplayObjectContainer : public DisplayObject
{
    public:
        DisplayObjectContainer();
        virtual ~DisplayObjectContainer();

    protected:

    private:
};

Any help would be appreciated. Thanks!

TommyX
  • 83
  • 2
  • 12
  • First, why does the parent class know about a specific derived class? Regardless, you'll need to use a forward declaration in the header containing `DisplayObject` (which will only have a `DisplayObjectContainer*` that is not dereferenced) and put the `include` in the source file (e.g., `DisplayObject.cpp`) for `DisplayObject`. – James Adkison Apr 26 '16 at 03:25

1 Answers1

1

There are a couple of ways to solve your problem, the simplest being to simply split up the DisplayObject into separate class and class-implementation. So you have the class defined in a header file, and the implementation of the member function in a separate source file.

That way the header file for DisplayObject don't need the header file for DisplayObjectContainer, all that's needed is the forward declaration of the DisplayObjectContainer class.

Something like this in the header file

#pragma once

// Forward declaration of the class
class DisplayObjectContainer;

class DisplayObject
{
private:
    DisplayObjectContainer *parent;
    ...
};

And in the source file you include the header files:

#include "DisplayObject.h"
#include "DisplayObjectContainer.h"

// Here you can use the members of DisplayObjectContainer

A harder way is to change the design so that DisplayObject doesn't actually need to know in which container it's stored. This decoupling is probably better in the long run, but like mentioned needs a redesign of your project.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Shouldn't this just be closed as a duplicate? – James Adkison Apr 26 '16 at 03:30
  • Thank you! The first suggestion solved the problem. For the second suggestion, I would consider redesigning it, although the structure I am following is the exact same structure Adobe Flash has. – TommyX Apr 26 '16 at 03:49