Jump to content
  • Advertisement
Sign in to follow this  
Sfpiano

Using 2 Classes that include each other

This topic is 5059 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Basically here's what I have:
//Class A
#include "ClassB"

class A{
A(B)
}

//Class B
#include "ClassA"
B()...
private:
A;
Is there any way to make this work?

Share this post


Link to post
Share on other sites
Advertisement
you need a class declaration.


//Class A

#include "ClassB"



class A{

A(B)

}



//Class B

class ClassA;

B()...

private:

A;


note the "class ClassA". this tells the compiler "there is a class called ClassA out there, and you will know about him at compile time".

Share this post


Link to post
Share on other sites
because when you do forward declaration you can only create the object dinamically.

I mean:

class a;

class b
{
a myA; // <---wont work
};


You need to make myA a pointer:

class a;

class b
{
a* myA; // <---WILL work
b() //constructor
{
a = new a();
}

};

Share this post


Link to post
Share on other sites
Quote:
Original post by Sfpiano
Then it tells me I'm using an undefined class.


Because a class declaration only allows you to create pointers, references to that class, or to declare functions that return or take it as parameter.

Code that actually creates variable of the class type require a full definition, as there is no other way for the compiler to know the actual size of the variable.

In your example, since A only uses B as a function parameter, it can make do with a declaration for B. However, B has a member of type A (not A* nor A&) and thus needs the full definition for A.

Share this post


Link to post
Share on other sites
then add a constructor B::B(){} to your class.

and make it public! I wonder why it doesn't use the default one.

ah, don't forget to do #include "B.h" in A.cpp

Share this post


Link to post
Share on other sites
Ok, here's my code:

//Graph.h
#include "Geo.h"
class Graph {
public:
Graph();
Graph( Geo &obj );
...
}

//Geo.h
class Graph;

class Geo {
private:
Graph* graph;
...
}

//Geo.cpp
Geo::Geo() {
graph = new Graph();
}


And it tells me Graph has no constructors.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!