0

Please help to figure out whats wrong with this code.

main.cpp create Object3D which create Box and pass Object3D* pointer to Box.

And there are errors until i remove Object3D declarations from Box.

main.cpp


#include <iostream>
#include "stdafx.h"
#include "Object3D.h"


int _tmain(int argc, _TCHAR* argv[])
{
    Object3D obj;

    char c;
    std::cin >> c;
    return 0;
}

Object3D.cpp


#include "Object3D.h"
#include "Box.h"

Object3D::Object3D()
{}

Object3D::~Object3D()
{}

Object3D.h


#ifndef OBJECT3D_H
#define OBJECT3D_H
#include "Box.h"

class Object3D
{
public:
    Object3D();
    ~Object3D();
private:
    Box _box_obj;  //<<<---ERROR HERE (C2146, C4430)
};

#endif

Box.cpp


#include "Box.h"
#include "Object3D.h"

int Box::Init(Object3D* _obj)
{
    obj = _obj;
}

Box::Box()
{}

Box::~Box()
{}

Box.h


#ifndef BOX_H
#define BOX_H
#include "Object3D.h"

class Box
{
public:
    Object3D* obj;  //<<<---ERROR HERE (C2143, C4430)

    int Init(Object3D* _obj);  //<<<---ERROR HERE (C2061)

    Box();
    ~Box();
};

#endif
barak manos
  • 29,648
  • 10
  • 62
  • 114
  • You appear to have a circular include problem. – Retired Ninja Apr 20 '14 at 09:40
  • In file `Object3D.h`, change `Box _box_obj` to `Box* _box_obj` (and then of course, fix the rest of your code to work with a `Box` pointer instead of a `Box` instance). – barak manos Apr 20 '14 at 09:42
  • unfortunately changing to "Box* _box_obj" gives same errors. its really circular include problem but i cant understand how to solve this problem, because i need parent class poiner to work with data. – user3017844 Apr 20 '14 at 09:47
  • possible duplicate of [Resolve circular dependencies in c++](http://stackoverflow.com/questions/625799/resolve-circular-dependencies-in-c) – Retired Ninja Apr 20 '14 at 09:54

1 Answers1

0

Change Box.h:

#ifndef BOX_H
#define BOX_H

// forward reference possible since the class is not dereferenced here.    
class Object3D;

class Box
{
public:
    Object3D* obj;

    int Init(Object3D* _obj);

    Box();
    ~Box();
};

#endif

The class definition does not use any member of Object3D. Therefore you don't need to know the definition of Object3D but just the fact that it is a class. The forward reference is sufficient and an appropriate tool to resolve a circular dependency.

BTW: The circular reference of object usually includes some "master" objects that own the other objects. It makes sense to change the member name to show the relation rather the type. I would suggest a

Object3D* owner;

when the box owns the obj.

harper
  • 13,345
  • 8
  • 56
  • 105