Search code examples
c++classheaderfriend-function

Redefinition of a class in C++


I'm new to C++ and stuck in a problem with an Error, called

"Semantic Issue: Redefinition of 'B' cB.h".

I have two classes, A and B, where cA should handle an Object of cB by reference and one friend function of cA, fExample. This is what the code looks like:

.h file cA:

#include "cB.h"

class A{
  int val1, val2;
public:
  friend void fExample(int, cB &);
};

.h file cB:

class B{
  int val1, val2;
public:
  void set_val1(int);
};

.cpp file cB:

#include <iostream>
#include "cB.h"
using namespace std;

void B::set_val1(int tVal){
  val1 = tVal;
}

For me, it seems there is no way of working with the cB-object by reference with a friend function of cA. I would know some workarounds, but that's not my intention, I want to learn how to handle this problem the right way.

So thanks in advance for helping!


Solution

  • This type of error often happen due to missing include guards. The Simplest way is:

    #ifndef HEADER_NAME
    #define HEADER_NAME
    

    You may also use #pragma once