Matin Lotfaliee Matin Lotfaliee - 1 month ago 7
C++ Question

Inline methods of two dependant structures?

I want to inline my two structures. But they have pointer of each other. Like the code below:

A.h

#ifndef A_H
#define A_H

#include "b.h"

struct A
{
B* b;
int value;

A();
void Inc();
};

#endif // A_H


A.cpp

#include "a.h"

A::A()
{
b = new B(this);
}

void A::Inc()
{
b->value++;
}


B.h

#ifndef B_H
#define B_H

struct A;

struct B
{
A* a;
int value;

B(A* a);
void Inc();
};

#endif // B_H


B.cpp

#include "b.h"
#include "a.h"

B::B(A *a)
{
this->a = a;
}

void B::Inc()
{
a->value++;
}


main.cpp

#include <iostream>
#include <a.h>

using namespace std;

int main()
{
A a;
a.value = 0;
a.b->value = 0;
a.Inc();
a.b->Inc();
cout << a.value << endl;
cout << a.b->value << endl;
return 0;
}


I can not use keyword
inline
anywhere because it gives me the error
undefined reference to methods
.

Based on here, I can define my methods in header files but that would force me to use
#include <a.h>
inside the file
b.h
. But that would give me another error because of duplicate includes.

Now How can I inline both Inc methods?

Answer

It's not possible to inline all member functions of two mutually dependent structs.

You have three options to implement the member functions.

Option 1

Use only forward declarations in the .h files. Implement all the functions in the .cpp files. None of the member functions are inlined.

Option 2

Use forward declaration of A in B.h but use full definition of B in A. In this case, all member functions of A can be inlined but member functions of B cannot be inlined. They will need to be implemented in a .cpp file.

Option 3

Reverse the roles of A and B from Option 2

Use forward declaration of B in A.h but use full definition of A in B. In this case, all member functions of B can be inlined but member functions of A cannot be inlined. They will need to be implemented in a .cpp file.

Comments