Getting two classes to use the other one's methods

I want to set up 2 classes.

Each class needs to be able to call methods from the other class.

What I tried first is this:

In the header of each class, I included the header of the other class.

This didn't work.

Next I tried to use forward declarations.

In each class, I declared an incomplete type of the other class.

I made sure to only use pointers of the incomplete type in the headers of both classes.

However, in the implementation, each class has a method which passes a pointer of the type of the other class.

Each class then dereferences the pointer and calls a method of that dereferenced pointer.

I didn't think this would work in the first place since incomplete types have no information of what methods are in that type, but I tried it anyway, and it didn't work.

How do I do this in c++?
Last edited on
In the header of each class, I included the header of the other class,

AND

In each class, I declared an incomplete type of the other class.

It worked, but can anyone explain why?
Last edited on
Why are you trying to do this? It sounds like poor design if you're doing this... Why not just create a super class with these methods you're trying to use, and have both these classes inherit from it?
I'm trying to make an animation where the next frame or step is updated by a thread in SFML

Specifically, I'm trying to make a physics simulation.

I will call the classes A, and B.

Class A already inherits from an sf::Thread. It counts steps at a constant rate while the main program is running.

Class B is an object that will have mass and kinetic energy. For now, it's only a container for an
sf::Drawable.

A will hold a vector of objects of type B. Every time a B is created, it is added to this list in A.

Every time A calculates the next step, it goes through the list, telling each B to update based on what step it is.

A needs to include B because it calls B::update(), and B needs to include A because it calls A::addToList(this) upon it's creation.

I suppose this would cause problems once there are hundreds of these B objects in A's list, but it's the only way I could think of making sure that each B calculates it's next step at the same rate as all the other B objects.

If I made a super class that inherited from sf::Thread, and made each B calculate it's next step independently of all other B objects, then they will be out of sync.

Is there a better way to go about this?
Last edited on
Topic archived. No new replies allowed.