Static function of some class as a friend of other class

A

Alex Vinokur

I want static functions of classes Uam and Bar to be friends of class
Foo.

There is no problem with Uam::uam().
But class Bar has a member of Foo type: member Bar::m_foo, so one can't
put Bar definition before Foo definition.

As a result, a compiler rejects
friend void Bar::bar(); // in class Foo

Is there any solution for this problem?

------ foo.cpp ------
class Uam
{
static void uam() {}
};

class Bar;

class Foo
{
friend void Uam::uam();
friend void Bar::bar();
};

class Bar
{
Foo m_foo;
static void bar() {}
};


int main()
{
return 0;
}

---------------------

------ Compilation ------
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 13.10.3077 for
80x86
Copyright (C) Microsoft Corporation 1984-2002. All rights reserved.

foo.cpp
foo.cpp(11) : error C2027: use of undefined type 'Bar'
foo.cpp(6) : see declaration of 'Bar'
-------------------------



Thanks,

Alex Vinokur
email: alex DOT vinokur AT gmail DOT com
http://mathforum.org/library/view/10978.html
http://sourceforge.net/users/alexvn
 
M

mlimber

Alex said:
I want static functions of classes Uam and Bar to be friends of class
Foo.

There is no problem with Uam::uam().
But class Bar has a member of Foo type: member Bar::m_foo, so one can't
put Bar definition before Foo definition.

As a result, a compiler rejects
friend void Bar::bar(); // in class Foo

Is there any solution for this problem?

------ foo.cpp ------
class Uam
{
static void uam() {}
};

class Bar;

class Foo
{
friend void Uam::uam();
friend void Bar::bar();
};

class Bar
{
Foo m_foo;
static void bar() {}
};


int main()
{
return 0;
}

---------------------

------ Compilation ------
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 13.10.3077 for
80x86
Copyright (C) Microsoft Corporation 1984-2002. All rights reserved.

foo.cpp
foo.cpp(11) : error C2027: use of undefined type 'Bar'
foo.cpp(6) : see declaration of 'Bar'
-------------------------

See this FAQ:

http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.12

In essence, you'll need to reverse the order of your classes: forward
declare Foo, then define Bar making Bar::m_foo a pointer (preferably a
smart pointer such as std::tr1::scoped_ptr aka boost::scoped_ptr), and
then define Foo.

Cheers! --M
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top