-1

I'm writing a game engine (using SFML libraries) and I can't seem to get this to work. I'm writing the GUI portion of code and I want to declare a object of the same class inside itself (parent/child so I can link objects together). I can't do this unless the class is finished being instantiated. Is there some sort of makeshift way I can force the child and parent variables to somehow work?

#ifndef ELEMENT_H
#define ELEMENT_H

#include <iostream>

class Element
{
    public:
        Element();
    private:
        int id, position_x, position_y, pixel_x, pixel_y, width, height;

        Element parent;
        std::vector<Element> child;
};

#endif // ELEMENT_H

Error I get:

include\Element.h|13|error: field 'parent' has incomplete type 'Element'|
Jezor
  • 3,253
  • 2
  • 19
  • 43
Honor
  • 63
  • 2
  • 9
  • If you could do that, `Element` would have infinite size. – melpomene Jun 24 '16 at 16:03
  • OOoh, good point.. What if I made them undeclared pointers? – Honor Jun 24 '16 at 16:03
  • Does implementation file exist? If it doesn't, you can change parent to be a reference: `Element& parent` and have it initialized in the constructor initialization list. – Jezor Jun 24 '16 at 16:04

2 Answers2

2

You cannot declare a set variable of type Class <x> within itself like you have there.

You can, however, have a class that contains a data member that is a pointer to itself...

#ifndef ELEMENT_H
#define ELEMENT_H

#include <iostream>

class Element
{
    public:
        Element();
    private:
        int id, position_x, position_y, pixel_x, pixel_y, width, height;

        Element *parent;
        std::vector<Element *> child;
};

#endif // ELEMENT_H
m_callens
  • 6,100
  • 8
  • 32
  • 54
1

You can make parent of type Element* (or std::shared_ptr<Element> if you want to use the smart pointers feature of c++11/boost)

Can you imagine the problem of having an Element with an Element inside it and an Element inside it? It would never end. Typically chains like this have one Element that is the root, where parent = NULL.

Assimilater
  • 944
  • 14
  • 33