0

I have the following code in c++

ChildObject.h

#pragma once
#include "ParentObject.h"

class ChildObject
{
public:
    ChildObject();
    void addParent(const ParentObject &po);

};

ParentObject.h

#pragma once

#include "ChildObject.h"

class ParentObject
{
public:
    ParentObject();
    void addChildren();
};

ChildObject.cpp

#include "ChildObject.h"

ChildObject::ChildObject() {

}

void ChildObject::addParent(const ParentObject& po) {

}

ParentObject.cpp

#include "ParentObject.h"

ParentObject::ParentObject() {

}

void ParentObject::addChildren() {
    ChildObject c1;
    c1.addParent(*this);
}

Makefile

test:  ParentObject.o ChildObject.o main.o
        gcc test ParentObject.o ChildObject.o main.o

ParentObject.o: ParentObject.cpp ParentObject.h
        gcc ParentObject.cpp -o ParentObject.o

ChildObject.o: ChildObject.cpp ChildObject.h
        gcc ChildObject.cpp -o ChildObject.o


main.o: main.cpp
        gcc main.cpp -o main.o

main.cpp is just an empty file

When I compile it I get the errors:

‘ParentObject’ does not name a type in line 8 of ChildObject.h cannot convert ‘ParentObject’ to ‘const int&’ line 9 of ParentObject.cpp

This is compiled with gcc (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0

I am at a loss as to what this means and any help would be appreciated.

APA
  • 164
  • 1
  • 5
  • 1
    You appear to have circular includes in the header files. Child includes Parent and Parent includes Child but it doesn't need to. You should remove that include. You can still include both or either in cpp files as needed. – Retired Ninja Jun 17 '22 at 20:54
  • 2
    1. Your source should *precisely* note which *specific* content is in which *specific* files. 2. You have *circular header dependencies*, and a forward-decl + removing one header-to-header include side is the typical way to address that. – WhozCraig Jun 17 '22 at 20:56
  • Many thanks for the response. I neglected the code which I think necessitates the circular references – APA Jun 17 '22 at 21:11
  • Same thing with the new code. Remove `#include "ChildObject.h"` from the parent header and add it to the parent cpp file. – Retired Ninja Jun 17 '22 at 22:55
  • Many thanks - that's it. I suppose only put the header where you really need it. – APA Jun 18 '22 at 08:44

0 Answers0