AudioDroid
AudioDroid

Reputation: 2322

Why does friend class crash on static function call?

#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?

Upvotes: 1

Views: 521

Answers (5)

Muhammad Usama
Muhammad Usama

Reputation: 3117

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

class CFriend
{
public:

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

Upvotes: 2

Dan
Dan

Reputation: 13382

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.

Upvotes: 2

IronMensan
IronMensan

Reputation: 6831

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.

Upvotes: 1

Bruce
Bruce

Reputation: 7132

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

You must explicitely call your friend class :

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

Upvotes: 2

kravemir
kravemir

Reputation: 11026

You've created infinite recursion:

void privateFunc(){privateFunc();};

Use instead:

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

There's nothing wrong with friend declaration.

Upvotes: 6

Related Questions