Click here to Skip to main content
15,890,123 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how to solve the problem of cyclic dependency such as below

C++
class cfoobar
{
     // ... refers to class cgoobar members ...
}

class cgoobar
{
     // ... refers to class cfoobar members ...
}


What I have tried:

C++
// pass cgoobar as a template parameter

template<class T=cgoobar>
class cfoobar {}


C++
// refer to cgoobar member via a cgoobar pointer
class cgoobar;
class cfoobar
{
public:
	void foobar_method()
	{
		auto goobar_ptr = new cgoobar; // error: use of undefined type 'cgoobar'
		goobar_ptr->goobar_method();
	}
};

class cgoobar
{
public:
	void goobar_method() { }
};
Posted
Updated 15-Dec-20 16:49pm
v3

You need to use forward declaration:

C++
class cgoobar;
class cfoobar
{
     // ... refers to class cgoobar ...
public:
    cgoobar* ptr;
}

class cfoobar; // not exactly needed but required 
//if the class declared in different translation unit
class cgoobar
{
     // ... refers to class cfoobar ...
public:
    cfoobar* ptr;
}
 
Share this answer
 
v2
Comments
CPallini 15-Dec-20 16:54pm    
5.
This is because you instantiate cgoobar, it needs cgoobar information such as its class size, forward declaration cannot help you. Forward declaration can only help when declaring cgoobar pointer in header because pointer size is always the same (32-bit or 64-bit depending on the platform). One solution is to put your class in header and functions in their own cpp file.

C++
// put this code inside cfoobar.h
class cfoobar
{
public:
	void foobar_method();
};

C++
// put this code inside cgoobar.h
class cgoobar
{
public:
	void goobar_method();
};

C++
// put this code inside cfoobar.cpp
#include "cfoobar.h"
#include "cgoobar.h"

void cfoobar::foobar_method()
{
	auto goobar_ptr = new cgoobar;
	goobar_ptr->goobar_method();
}

C++
// put this code inside cgoobar.cpp
#include "cgoobar.h"

void cgoobar::goobar_method()
{
}
 
Share this answer
 
v2
Define cgoobar before cfoobar.

C++
class cgoobar
{
public:
	void goobar_method() { }
};

class cfoobar
{
public:
	void foobar_method()
	{
		auto goobar_ptr = new cgoobar; // error: use of undefined type 'cgoobar'
		goobar_ptr->goobar_method();
	}
};
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900