0

The following simple application demonstrates the compile error:

My class declaration: MyClass.h

#pragma once
class MyClass
{
   friend int MyCalc();
public:
};

class definition: MyClass.cpp

#include "stdafx.h"
#include "MyClass.h"

int MyCalc()
{
   return 1 + 2;
}

The main function: ConsoleApplication1.cpp

#include "stdafx.h"
#include "MyClass.h"
#include <iostream>

int main()
{
   std::cout << MyCalc();//"Identifier MyCalc is undefined" in Visual Studio 2019, but not in 2015
    return 0;
}

I'm guessing the updated c++ version has made this more restrictive. So will I have to add a declaration of the function outside of the class everywhere I have a friend function declared, like so:

class MyClass
{
   friend int MyCalc();
public:
};
int MyCalc();
Jana Andropov
  • 121
  • 11

1 Answers1

3

This is the clause, found in [namespace.memdef], that is causing the name MyCalc() not to be found inside main(), and it has been part of standard C++ for as long as there has been a C++ Standard.

Every name first declared in a namespace is a member of that namespace. If a friend declaration in a non-local 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 simple name lookup until a matching declaration is provided in that namespace scope (either before or after the class declaration granting friendship).

Older versions of the Visual C++ compiler may not have enforced this rule correctly, but your code is in error and always has been and Visual Studio 2019 is correct to tell you this.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720