-4

Compiler issues an error that the identifier "func" is undefined:

enter image description here

I don't know why this error occurs because I link the header file, with the declaration of this function. I use Visual Studio 2017 Community.

My code:

foo.h

#pragma once

class Foo {
    friend void func();
};

foo.cpp

#include "foo.h"

void func()
{
}

bar.h

#pragma once

class Bar {
    void baz();
};

bar.cpp

#include "bar.h"
#include "foo.h"

void Bar::baz()
{
    func(); // indentifier "func" is undefined
}
iBug
  • 35,554
  • 7
  • 89
  • 134
Maksym
  • 3
  • 2
  • 2
    Edit your question, show the error, correct your spelling. And wrong, header is not for linking. –  Mar 25 '18 at 16:43
  • Add the declaration `void func(void);` to "foo.h". – DYZ Mar 25 '18 at 16:43
  • Mind showing where you defined func? because it isn't in your question hence your error. – AresCaelum Mar 25 '18 at 16:45
  • Your `foo` class needs the declaration of `func` before the class. Use a forward declaration. – Thomas Matthews Mar 25 '18 at 16:50
  • 1
    This `friend void func();` is **not a declaration**. – eesiraed Mar 25 '18 at 16:53
  • Alright I will try to explain this simply, bar and foo are not related in any way, you have not listed any of them as being a friend class, so your error is because bar is trying to access a func definition from the bar class (Which is not declared or defined). not foo(like you believe it is), and bar also has no instances of foo to call that method. – AresCaelum Mar 25 '18 at 16:55

1 Answers1

1

Declare the function.

void func();

Declaring a function as friend to a class does not declare the function to anything else - the function will only be visible to class Foo. So you should actually declare that function.

To be less confusing: Declaring the existence of a function is different from declaring its friendship to a class.

iBug
  • 35,554
  • 7
  • 89
  • 134