I am getting the below error, when i am trying to compile code below.
Error: main.cpp: In function "int main()":
main.cpp:6: error: "display" was not declared in this scope
test1.h
#include<iostream.h>
class Test
{
public:
friend int display();
};
test1.cpp:
#include<iostream.h>
int display()
{
cout<<"Hello:In test.cc"<< endl;
return 0;
}
main.cpp
#include<iostream.h>
#include<test1.h>
int main()
{
display();
return 0;
}
Strange thing is I am able to compile in unix successfully. I am using gcc and g++ compiler
You need to provide the declaration for the function before declaring it as friend.
The declaration as friend does not qualify as actual function declaration as per the standard.
C++11 standard §7.3.1.2 [namespace.memdef]:
Para 3:
[...] If a
frienddeclaration in a nonlocal class first declares a class or function the friend class or function is a member of the innermost enclosing namespace. The name of the friend is not found by unqualified lookup or by qualified lookup until a matching declaration is provided in that namespace scope (either before or after the class definition granting friendship). [...]
#include<iostream.h>
class Test
{
public:
friend int display(); <------------- Only a friend declaration not actual declaration
};
You need:
#include<iostream.h>
int display(); <------- Actual declaration
class Test
{
public:
friend int display(); <------- Friend declaration
};
Interesting. It looks like the friend declaration for display() in test1.h counts as an actual function declaration in g++.
I do not think the standard actually enforces this, so you probably want to add a proper declaration for display() in test1.h:
#include <iostream>
int display();
class Test
{
public:
friend int display();
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With