1
#include <iostream>

using namespace std;

class CClass
{
private:
   friend class CFriend;
   static void privateFunc(){std::cout << "privateFunc" << std::endl;};
};

class CFriend
{
public:

   void privateFunc(){privateFunc();};
};

int main(int argc, char* argv[])
{
   CFriend b;
   b.privateFunc();
   return 0;
}

This code compiles, but using the gcc-compiler or http://www.ideone.com/ the program crashes. Is that a compiler error or do I need to understand more about friend classes?

AudioDroid
  • 2,292
  • 2
  • 20
  • 31

5 Answers5

6

You've created infinite recursion:

void privateFunc(){privateFunc();};

Use instead:

void privateFunc(){CClass::privateFunc();};

There's nothing wrong with friend declaration.

kravemir
  • 10,636
  • 17
  • 64
  • 111
2

You have the function called privateFunc() in CFriend class as well. This means when inside that function you call privateFunc() it will call itself (how should it know you mean the other class) thus entering a recursive infinite loop.

You mean

void privateFunc()
{
  CClass::privateFunc();
}

using CClass:: to specify completely the name of the function you mean.

aardvarkk
  • 14,955
  • 7
  • 67
  • 96
Dan
  • 12,857
  • 7
  • 40
  • 57
2

Infinite recursion in your object, creating a Stack Overflow !!!

You must explicitely call your friend class :

void privateFunc(){CClass::privateFunc();};
Bruce
  • 7,094
  • 1
  • 25
  • 42
2

It is crashing because of stack overflow you would beed scope resolution to call static function

class CFriend
{
public:

   void privateFunc(){CClass::privateFunc();};
};
Bo Persson
  • 90,663
  • 31
  • 146
  • 203
Muhammad Usama
  • 2,797
  • 1
  • 17
  • 14
1

You have a stack overflow from an infinitely recursive function. CFriend::privateFunc is calling itself. Change it to void privateFunc() {CClass::privateFunc();}

Scope distinctions, public, private, protected and friend, have not runtime consequences at all. They are strictly for the compilier to decide what is legal or not. You could #define private public and the resulting executable wouldn't change.

IronMensan
  • 6,761
  • 1
  • 26
  • 35