Classes using each other? - c++

I have 2 header files that contain 2 classes. Each class is dependent on other, like so:
// class1.h
#include "class2.h"
class ClassOne {
ClassTwo* c2;
};
// class2.h
#include "class1.h"
class ClassTwo {
ClassOne* c1;
};
I expected the code not to compile, so I added a forward declaration to one of the headers:
// class1.h
#include "class2.h"
class ClassTwo;
class ClassOne {
ClassTwo* c2;
};
But sadly that isn't working, either. I keep getting compiler errors for "use of undefined type 'ClassTwo'".
I know I can just combine them into one header file and they will work, but in reality they are both really big classes and I really would prefer they have their own header file for organization purposes.
Is there a way to get around this?
Thanks,
Alex

You added the forward declaration but didn't remove the include. Do that and you're golden.
Actually, remove both includes, and replace them with forward declarations.
// class1.h
class ClassTwo;
class ClassOne {
ClassTwo* c2;
};
// class2.h
class ClassOne;
class ClassTwo {
ClassOne* c1;
};
Note that cases where circular dependencies are actually required are few and far apart, so at least review the design.

Related

Resolving circular dependencies from inheritance

Is it not possible to include the baseclass header and have it include all of its subclasses through it?
I seem to have come to an circular dependency with my base class and its subclasses.
From the program entry, I need to initialize one of the subclasses based on user input. I thought I could include the header of the base class which includes the headers of the subclasses:
main.cpp
#include "baseclass.h"
int main()
{
...
}
baseclass.h
#include "sub1.h"
class Base
{
public:
int name;
};
sub1.h
#include "baseclass.h"
class Base; // forward declaration
class Sub : public Base
{
public:
int age;
};
So the dependency is:
main -> baseclass -> sub1 -> baseclass -> sub1 -> etc...
If I keep the forward declaration in, g++ -std=c++11 -o prog *.cpp throws:
error: invalid use of incomplete type 'class Base'
Removing:
error: expected class-name before '{' token {
Not sure how to resolve this without putting a middle "factory" that includes all the subclass headers which each include the baseclass header.
Remove the #include "sub1.h" from baseclass.h, and create a separate header file, which includes all the derived classes you need, and include this header file into main.cpp.
Note: this line class Base; // forward declaration is not needed.
Remove #include "sub1.h" from base.h (also the class Base forward declaration). Where you wan't to use sub include sub1.h, in this case in the main. If you are actually building a bunch of sub type child classes then in all likelihood you will implement something to create them correctly anyway. That something would probably be a factory. It will look something like this:
// ClassFactory.h
#include "sub1.h"
#include "sub2.h"
...
#include "subN.h"
std::unique_ptr<Base> createClass(std::string name) {
if (name == "sub1")
return std::unique_ptr<Base>(new sub1());
if (name == "sub2")
return std::unique_ptr<Base>(new sub1());
...
return nullptr;
}
And your main will include and use this file:
#include "ClassFactory.h"
int main(int argc, char** argv)
{
...
std::unique_ptr<Base> myClass = createClass(argv[1])
Big note: All pseudo code.
Then you will have solved the problem of creating a complex set of child classes at runtime and your problem of how to include all of them.
If you want base.h to include sub1.h, that is possible only after the definition of class Base :
#ifndef BASE_H_
#define BASE_H_
class Base
{
public:
int name;
};
#include "sub1.h"
#endif
It's obvious that this removes the need for a forward declaration of Base; at the point of inclusion it's fully defined.

Cyclic dependency and inheritance compilation error on c++

I have a problem in C++ that involves circular dependencies and inheritance.
I have implemented the design in parts and I will use pesudocode to ilustrate where the problem happens.
The first part is:
//app.h
include rel.h
class Rel; // forward declaration
class App {
shared_ptr<Rel> //member variable
}
//rel.h
include app.h
class App; //forward declaration
class Rel {
shared_ptr<App> //member variable
}
Until here, the program compiles without warnings
Then, I want to add inheritance as follows:
//app.h
include rel.h
include drel.h
class Rel; // forward declaration
class DRel // forward declaration
class App {
shared_ptr<Rel> //member variable
shared_ptr<DRel> //member variable
}
//rel.h (the same as before)
include app.h
class App; //forward declaration
class Rel {
shared_ptr<App> //member variable
}
//drel.h
include app.h
include rel.h
class App; //forward declaration
class DRel: Rel { // compile error here: expected class name before { token
shared_ptr<App> //member variable
}
As you see, the compiler throws "expected class name before { token" which means that Rel is not resolved, but why the first code without inheritance works and the second one doesn't? How can I fix that? Is that a "wrong" pattern?
I am using c++14
I know there are a lot of questions regarding the issues I am having, but I can't find the answer to my specific problem. Maybe I don't see it...
Since all the variables you declare do not need to know the space occupied by App, Rel and DRel, you don't even need to #include the headers in question, you just have to forward declare the name as you do.
So you have you .h with
class A;
class B;
class C {
std::shared_ptr<A> ptra;
std::shared_ptr<B> ptrb;
};
And then your .cpp with
#include "A"
#include "B"
C::C() { ... }
The original headers files needed to be guarded by #ifdefs like this:
#ifndef CYCLIC_DEPENDECY_1
#define CYCLIC_DEPENDECY_1
#include "cyclic_dependency2.h"
class Rel; // forward declaration
class App {
std::shared_ptr<Rel> test; //member variable
};
#endif
#ifndef CYCLIC_DEPENDECY_2
#define CYCLIC_DEPENDECY_2
#include "cyclic_dependency1.h"
class App; //forward declaration
class Rel {
std::shared_ptr<App> test;//member variable
};
#endif
#include <iostream>
#include <memory>
#include "cyclic_dependency2.h"
class Rel; // forward declaration
class DRel; // forward declaration
class DRel: Rel {
std::shared_ptr<App> test ;//member variable
};
main()
{
}

How to forward declare a custom constructor?

Note: I have found the issue with how my Xcode was compiling the below and it appears unrelated to the topic discussed herein. When I have more details I will provide them here.
I recommend voting to close my question as "too localized" since it was an Xcode problem, unrelated to the c++ code itself. Many thanks for the help all the same as I did learn from the answers.
The below question (now answered and resolved) was caused by a confusing exclusion of a file from the Xcode target, thus there were no compiler errors even though the file had problems.
I have a pure virtual interface and want to define its factory method, which returns a subclass of this interface. This works fine:
struct MyVirt{
...all virtual stuff
};
class SubVirt; //forward declaration allows factory:
MyVirt*CreateClass(){
return new SubVirt;
}
Update: Some of the comments say that forward declare is not enough to achieve the above, but that's not correct. You can accomplish the above fine without the full definition of the SubVirt class.
Now, what I want to do is have a custom constructor that takes arguments. As such:
MyVirt*CreateClass(){
return new SubVirt(arg 1, etc);
}
The problem is that a class forward declaration is no longer sufficient. It needs to see the class definition or its header. This means I can either move the factory method to the file where SubVirt is defined, or I have to include that file in the above file, which creates a circular dependency.
Is there a way to forward declare the custom constructor instead? That would make it all much simpler.
Your CreateClass function looks odd, you miss () in function definition. Should be like this:
MyVirt* CreateClass()
{
return new SubVirt(arg 1, etc);
}
When return a pointer, compiler needs to know the concrete type and constructor, so forward declare is not enough.
What you could do is:
in header file: forward declare SubVirt and CreateClass function
cpp file: include MyVirt.h and define CreateClass function
Separate declaration from implementation, like everyone does.
MyVirt.h:
struct MyVirt{
...all virtual stuff
};
MyVirt.cpp:
#include "MyVirt.h"
Implementation of MyVirt
SubVirt.h:
#include "MyVirt.h"
struct SubVirt : MyVirt {
...all SubVirt stuff
};
SubVirt.cpp:
#include "SubVirt.h"
Implementation of SubVirt
Factory.h:
struct MyVirt;
MyVirt *CreateClass();
Factory.cpp:
#include "SubVirt.h"
MyVirt *CreateClass() { return new SubVirt() }
This can be accomplished by separating the declaration and implementation.
The key here is to put the definition/implementation above the includes. Suppose you want to separate the classes A and B create two files like the following:
A.hpp
#ifndef A_HPP
#define A_HPP
struct B; // fwd. decl.
struct A {
int v;
A(int v) {
this->v = v;
}
B* createB();
};
#include "B.hpp"
A* B::createA() {
return new A(v);
}
#endif A_HPP
B.hpp
#ifndef B_HPP
#define B_HPP
struct A; // fwd. decl.
struct B {
int v;
B(int v) {
this->v = v;
}
A* createA();
};
#include "A.hpp"
B* A::createB() {
return new B(v);
}
#endif // B_HPP
main.hpp
#include <A.hpp>
#include <B.hpp>
#include <iostream>
int main(int argc, char *argv[]) {
A a(42);
std::cout << a.createB()->createA()->v << std::endl;
return 0;
}
You are of course free to move the implementation into a cpp file instead. This is only the basic recipe which shows how circular dependencies can be solved even for templated classes and functions.
http://codepad.org/IsBzQANX

Circular Class Dependency with Includes

Here is basically what my class layout is:
GameDriver.h:
#ifndef GAMEDRIVER_H
#define GAMEDRIVER_H
#include "CameraSystem.h"
class CameraSystem; //Forward declaration
class GameDriver {
//Stuff
};
#endif
CameraSystem.h:
#ifndef CAMERASYSTEM_H
#define CAMERASYSTEM_H
#include "Tickable.h"
class GameDriver;
class CameraSystem: public Tickable { //Complains here
//Stuff
};
#endif
Tickable.h:
#ifndef TICKABLE_H
#define TICKABLE_H
#include "GameDriver.h"
class GameDriver;
class Tickable {
//Stuff
};
#endif
Here is the error I get:
CameraSystem.h:9 error: expected class-name before '{' token
Forward declaring Tickable does not work either. Any help? Thanks in advance.
If you forward delcare a class you shouldn't include the class' header.
#include "CameraSystem.h" // DO NOT INCLUDE THIS
class CameraSystem; //Forward declaration
class GameDriver {
//Stuff
};
Ok, I see two problems here.
First: Your forward declarations are useless. You are writing (using GameDriver.h: as an example):
#include "CameraSystem.h"
class CameraSystem; //Forward declaration
class GameDriver {
//Stuff
};
Here CameraSystem will already be known by including CameraSystem.h, so the forward declaration is nonsense. What you meant to write was:
class CameraSystem; //Forward declaration
class GameDriver {
//Stuff
};
Second: Where you really would need a forward declaration you cannot use it, as you cannot derive from a forward declared class:
#include "Tickable.h"
class CameraSystem: public Tickable { //Complains here
//Stuff
};
Note that a forward declaration works only if you are not using the forward declared class directly as a class member. You are then restricted to pointers or references to the forward declared class. The reason for this is, that the compiler does not know the memory layout of the class unless its completely known (i.e. by including the header file). For example:
class CameraSystem;
class GameDriver {
CameraSystem m_cameraSystem;
};
will NOT work. However,
class CameraSystem;
class GameDriver {
CameraSystem *m_cameraSystem;
CameraSystem& m_otherCameraSystem;
};
will. Of course you will still have to include the correct header files in your *.cpp file.
You can't resolve such circular dependencies. However, you've got the solution (partially):
I.e. instead of including a header, just use a forward declaration. If you do this right, there shouldn't be any issues. However, try to group your program into logical elements/groups and only add cross-references if they're requied (e.g. the game has to know about and access the camera, but the camera shouldn't have to access the game system as a whole).
You can't inherit from a class that has not been declared.
Pre-processing Tickable.h gives you:
class GameDriver;
class CameraSystem: public Tickable { //Complains here
//Stuff
};
class CameraSystem; //Forward declaration
class GameDriver {
//Stuff
};
class GameDriver;
class Tickable {
//Stuff
};
See how Tickable hasn't even been forward declared when you inherit from it?
Try adding #pragma once at the very beginning of each header file.
You should somehow tell the compiler to only put those once. That's one way. Another is using #ifndef X and #define X.
If this doesn't solve it, try to just eliminate the circular dependency - it doesn't seem like it has to happen...

C++ class, its base class and circular include includes [duplicate]

This question already has answers here:
Resolve build errors due to circular dependency amongst classes
(12 answers)
Closed 4 years ago.
FILE #1 (foo.h):
#ifndef FOO_H_
#define FOO_H_
#include "baseclass.h"
#include "bar.h"
class Bar;
class Foo : public baseclass {
public:
bar *varBar;
};
#endif
FILE #2 (bar.h):
#ifndef BAR_H_
#define BAR_H_
#include "foo.h"
class Foo;
class Bar {
public:
Foo *varFoo;
};
#endif
FILE #3 (baseclass.h):
#ifndef BASECLASS_H_
#define BASECLASS_H_
#include "foo.h"
class Foo;
class baseclass {
public:
list<Foo*> L;
};
#endif
But I get an compile error in file #1 in line class Foo : public baseclass:
Error: expected class-name before »{« token
If I add class baseclass; bevor class declaration, I get this error:
Error: invalid use of incomplete type »struct baseclass«
So my question is, how can I resolve circular dependencies with baseclasses?
Ask if you don't get somepoint. I allready tried to change the order of includeing the headers, but no luck so far.
Thanks for any hint.
EDIT: Note: I am using include guards
EDIT2: It is not limited to pointers, so I remove them, just in case.
EDIT3: Added baseclass (forgot O.o)
EDIT4: Now it should be clear and without anymore flaws, the problem persisits with this code.
The usual way is to add the following around your header files:
#ifndef FOO_H_
#define FOO_H_
#include "baseclass.h"
#include "bar.h"
class Bar;
class Foo : public baseclass {
public:
bar *varBar;
};
#endif
and
#ifndef BAR_H_
#define BAR_H_
#include "foo.h"
class Foo;
class Bar {
public:
Foo *varFoo;
};
#endif
Most compilers (gcc, VC) also accept #pragma once at the beginning of the file, but I'm pretty sure it is not part of the current C++ standard.
EDIT:
Sure enough, as the ISO/IEC 14882 states, a #pragma "causes the implementation to behave in an implementation-defined manner. Any pragma that is not recognized by the implementation is ignored."
It is currently still the same with C++0x.
So I would stick with the first old-fashioned way of doing that ;-)
What you seem to have posted is to have a Bar member in the Foo, and a Foo member in the Bar. That is a circular dependency you need to break - if every Foo contains a Bar which contains a Foo then constructing either never terminates.
class Foo : public baseclass {
public:
Bar varBar;
};
class Bar {
public:
Foo varFoo;
};
Instead you need to use a pointer or reference to the Foo or Bar in at least one of them:
class Bar;
class Foo : public baseclass {
public:
Bar& varBar;
};
class Bar {
public:
Foo varFoo;
};
As the circularity is broken and you're only using a reference to the object, you don't need to have the full definition of the referred-to type, and can use a forward declaration.
Include guards are good for users, but try and not rely on them when developing. If the compiler has to check whether or not something has been included, it's still doing work even if it has optimisations for guards/pragmas. You do need to have some understanding of what depends on what to break the initial cycle, and putting guards on the files won't help you with that.
Do you have include guards on your headers? The code above includes a.h and b.h recursively, thus defining a whole bunch of headers.
The forward declaration class b; removes the need for the #include "b.h" in FILE1. Similarly, #include "a.h" should be removed from FILE2.
#ifndef _BAR_H_
#define _BAR_H_
#include "baseclass.h"
class Bar;
class Foo : public baseclass {
public:
Bar *varBar;
};
#endif
If a class is forward declared and you are using only a pointer or a reference to a member of that class, then you do not need to include the header for it. The same goes for the class in the other file. But yes, make sure that you use include guards in all of your header files (#ifndef...#endif) to prevent multiple inclusions of headers during compilation.
baseclass.h doesn't need anything from foo.h, so remove #include "foo.h" from baseclass.h.
You have a Foo variable in your Bar, and a Bar in your Foo. That isn't going to work: you can't have an egg in a box and a box in an egg. One or both of them should be a pointer.