oren revenge oren revenge - 4 months ago 28
C++ Question

How to declare declare a class friend to another before its definition

I have those two classes and I want the edge node to be friend for graph but I dont know how to declare it

The implementation of the graph is based on adjacency lists, I used unique_ptr for the auto deletion.

#ifndef GRAPH_HPP
#define GRAPH_HPP

#include <memory>
using std::unique_ptr;

template<typename Type>
class edgenode {
friend class graph<Type>; //here
edgenode(Type w, int adj);
~edgenode() {};
Type mWeight;
int mAdj;
unique_ptr<edgenode<Type>> mNext;

template<typename Type>
edgenode<Type>::edgenode(Type w, int adj)
:mWeight(Type), mAdj(adj) {
mNext = nullptr;


template<typename Type>
class graph {
graph(int maxvertices = 1000, bool directed = false);
unique_ptr<edgenode<Type>>* mEdges;
int* mDegree;
int mNoOfNodes;
int mNoOfVertices;
int mSize;
bool m_bDirected;

template<typename Type>
graph<Type>::graph(int maxvertices = 1000, bool directed = false)
: mSize(maxvertices),
mDegree = new int[mSize];
mEdges = new unique_ptr<edgenode<Type>>[mSize];

for (int i = 0; i < mSize; ++i) {
mDegree[i] = 0;
mEdges[i] = nullptr;

template<typename Type>
graph<Type>::~graph() {
delete[] mEdges;
delete[] mDegree;


Forward declare the class template like this:

template<typename Type> class graph;

template<typename Type>
class edgenode {
    friend graph<Type>;
    // ...