Start New Discussion within our Software Development Community

Hi,
While writing program for making a member function of one class a friend of another, VC++ is shooting two errors.

The entire code is split across five files, 2 headers for two classes, 2 .cpp for the class members' definitions and 1 containing main() function.

The headers are as below

// this is adder.h
#include<iostream>
using namespace std;

class MyNumbers;

class Adder {
public:
	int add_nums(MyNumbers &ob);
};

And

// this is mynum.h

#include"adder.h"
class Adder;  // forward declaration
class MyNumbers {
private:
	int num1;
	int num2;
	
public:
	MyNumbers(int a=0, int b = 0);
	void display() const;
	friend int Adder ::add_nums(MyNumbers &ob);
};

When I complie the code, compiler shoots two errors as below
c:\program files\microsoft visual studio\myprojects\friends\adder.h(6) : error C2011: 'Adder' : 'class' type redefinition
friend_main.cpp
c:\program files\microsoft visual studio\myprojects\friends\adder.h(6) : error C2011: 'Adder' : 'class' type redefinition
mynum.cpp

Error persists even when I comment the forward declaration in mynum.h.

Please help me resolve this error.
Thanks in advance.

The issue is with your header files themselves, not the forward declaration(s). Your classes are getting defined multiple times, they only need to be defined once. Add macro protection / guards to your headers.

Here are a couple examples.

You will probably have to get rid of your forward declaration for adder in mynum.h. You are including the header directly above it which should accomplish the forward declaration.

This article has been dead for over six months. Start a new discussion instead.