Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: variable was not declared in this scope

Tags:

c++

c++builder

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

like image 464
Akhirul Islam Avatar asked May 18 '26 10:05

Akhirul Islam


2 Answers

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 friend declaration 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 
};
like image 95
Alok Save Avatar answered May 19 '26 22:05

Alok Save


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();
};
like image 22
Frédéric Hamidi Avatar answered May 19 '26 23:05

Frédéric Hamidi