I am in the process of moving all of my C++ Windows applications to Ubuntu Linux. This application runs fine on Visual Studio 2015 Community on Windows 7 OS. However, it gives an error when running in Code Blocks on Ubuntu Linux. I have replicated the error message I am getting using the following simple Person
class.
Error Message: 'comparePersonAge' was not declared in this scope
#ifndef Person_h
#define Person_h
#include <string>
class Person
{
private:
int age;
std::string name;
public:
Person(int a, std::string n) : age(a), name(n) {}
int getAge()
{
return age;
}
std::string getName()
{
return name;
}
inline friend bool comparePersonAge(const Person& p1, const Person& p2)
{
return p1.age < p2.age;
}
};
#endif
main.cpp
#include <iostream>
#include <algorithm>
#include <vector>
#include "Person.h"
int main()
{
Person p1(93, "harold");
Person p2(32, "james");
Person p3(67, "tracey");
std::vector<Person> v;
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
std::sort(v.begin(), v.end(), comparePersonAge);
std::cout << v[0].getAge() << " " << v[1].getAge() << " " << v[2].getAge() << std::endl;
}
On Windows machine, the output is: 32 67 93
as expected. On Linux, the error message is as written above.
Note: Someone else name DJR discusses this issue in this post: Friend function not declared in this scope error. However, his explanation is very vague I and don't follow his steps.
He writes:
Previous comment should have read: It is a bug on the the Linux side. The code should work as written. I have code right now that compiles fine on the Windows side and when I move it to the Linux side I get the same error. Apparently the compiler that you are using on the Linux side does not see/use the friend declaration in the header file and hence gives this error. By simply moving the friend function's definition/implementation in the C++ file BEFORE that function's usage (e.g.: as might be used in function callback assignment), this resolved my issue and should resolve yours also.
I don't know what he means by by moving the friend function's definition in the C++ file before the function's usage. What does this mean precisely?
The purpose of the friend
keyword is to make an exception to the access rules (protected
and private
), giving a class or function access to members not otherwise allowed.
So you can declare and define your comparePersonAge()
function outside of your class declaration, and use the friend
keyword inside the declaration, to give the function access to private members, age
specifically.
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