When should you use friend classes? [duplicate] - c++

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When should you use 'friend' in C++?
I have come to a stumbling block because of lack of documentation on friend classes. Most books just explain it briefly, e.g an excerpt from C++: the Complete Reference:
Friend Classes are seldom used. They are supported to allow certain special case situations to be handled.
And frankly, I have never seen a friend class in any good code made by an experienced C++ programmer. So , here is my list of problems.
Do Inherited Classes have the same friends as there base classes? e.g, if I declare class foo as a friend of class base, will class der (derived from base) also have foo as a friend?
What are the special case situations when a friend class should be used?
I am making a winapi wrapper in which I want to make class WinHandle a friend of class Widget (to access some protected members). Is it recommended? Or should I just access them using the traditional Get/Set functions?

Friend is used for granting selective access, just like the protected access specifier. It's also hard to come up with proper use case where use of protected is really useful.
In general, friend classes are useful in designs where there is intentional strong coupling: you need to have a special relationship between two classes. More specifically, one class needs access to another classes's internals and you don't want to grant access to everyone by using the public access specifier.
The rule of thumb: If public is too weak and private is too strong, you need some form of selected access: either protected or friend (the package access specifier in Java serves the same kind of role).
Example design
For instance, I once wrote a simple stopwatch class where I wanted to have the native stopwatch resolution to be hidden, yet to let the user query the elapsed time with a single method and the units to be specified as some sort of variable (to be selected by user preferences, say). Rather than, have say elapsedTimeInSeconds(), elapsedTimeInMinutes(), etc. methods, I wanted to have something like elapsedTime(Unit::seconds). To achive both of these goals, I can't make the native resolution public nor private, so I came up with the following design.
Implementation overview
class StopWatch;
// Enumeration-style class. Copy constructor and assignment operator lets
// client grab copies of the prototype instances returned by static methods.
class Unit
{
friend class StopWatch;
double myFactor;
Unit ( double factor ) : myFactor(factor) {}
static const Unit native () { return Unit(1.0); }
public:
// native resolution happens to be 1 millisecond for this implementation.
static const Unit millisecond () { return native(); }
// compute everything else mostly independently of the native resolution.
static const Unit second () { return Unit(1000.0 / millisecond().myFactor); }
static const Unit minute () { return Unit(60.0 / second().myFactor); }
};
class StopWatch
{
NativeTimeType myStart;
// compute delta using `NativeNow()` and cast to
// double representing multiple of native units.
double elapsed () const;
public:
StopWatch () : myStart(NativeNow()) {}
void reset () { myStart = NativeNow(); }
double elapsed ( const Unit& unit ) const { return elapsed()*unit.myFactor; }
};
As you can see, this design achieves both goals:
native resolution is never exposed
desired time unit can be stored, etc.
Discussion
I really like this design because the original implementation stored the multiple of native time units and performed a division to compute the elapsed time. After someone complained the division was too slow, I changed the Unit class to cache the dividend, making the elapsed() method (a little) faster.
In general, you should strive for strong cohesion and weak coupling. This is why friend is so little used, it is recommended to reduce coupling between classes. However, there are situations where strong coupling gives better encapsulation. In those cases, you probably need a friend.

Do Inherited Classes have the same friends as there base classes? e.g if i declare class foo as a friend of class base, will class der (derived from base) also have foo as a friend?
The rule with friend keyword is:
Friendship attribute is not inherited.
So No friend of base class will not be friend of Derived class.
What are the special case situations when a friend class should be used?
Frankly, (IMHO) using friend classes is mostly done to achieve some things for rather ease of usage. If a software is designed taking in to consideration all the requirememtens then there would practically no need of friend classes. Important to note perfect designs hardly exist and if they do they are very difficult to acheive.
An example case which needs friend class:
Sometimes there may be a need for a tester class(which is not part of the release software) to have access to internals of classes to examine and log certain specific results/diagnostics. It makes sense to use friend class in such a scenario for ease of usage and preventing overhead of design.
I am making a winapi wrapper in which I want to make class WinHandle a friend of class Widget (to access some protected members). Is it recommended? Or should I just access them using the traditional Get/Set functions?
I would stick to the traditional setter/getter. I rather avoid using friend where I can get working through usual OOP construct. Perhaps, I am rather paranoid about using friend because if my classes change/expand in future I perceive the non inheritance attribute of friend causing me problems.
EDIT:
The comments from #Martin, and the excellent answer from #André Caron, provide a whole new perspective about usage of friendship, that I had not encountered before & hence not accounted for in the answer above. I am going to leave this answer as is, because it helped me learn a new perspective & hopefully it will help learn folks with a similar outlook.

friend usually accounts for where you would normally use one single class, but you have to use more because they have different life-times or instance counts, for example. friendship is not transferred or inherited or transitive.
Get/Set is quite terrible, although better than it could be. friend allows you to limit the damage to just one class. Usually you will make an intermediary class which is friended.
class MyHandleIntermediary;
class MyHandle {
friend class MyHandleIntermediary;
private:
HANDLE GetHandle() const;
};
class MyWidget;
class MyHandleIntermediary {
friend class MyWidget;
static HANDLE GetHandle(const MyWidget& ref) {
return ref.GetHandle();
}
};
class MyWidget {
// Can only access GetHandle() and public
};
This allows you to change the accessibility of friendship on a per-member level and ensures that the extra accessibility is documented in a single place.

One of the cases where I applied the "friend classes", is where one class is composed or referenced by other (objects) classes, and the composing objects, require access to the internals of the main class.
enum MyDBTableButtonBarButtonKind {
GoFirst,
GoPrior,
GoNext,
GoLast
}
class MyDBTableButtonBarButtonWidget;
class MyDBTableButtonBarWidget {
friend class MyDBTableButtonBarButtonWidget;
// friend access method:
protected:
void GoFirst();
void GoPrior();
void GoNext();
void GoLast();
void DoAction(MyDBTableButtonBarButtonKind Kind);
};
class MyDBTableButtonBarButtonWidget {
private:
MyDBTableButtonBarWidget* Toolbar;
public:
MyDBTableButtonBarButtonWidget(MyDBTableButtonBarWidget* AButtonBar) {
this ButtonBar = AButtonBar;
}
MyDBTableButtonBarButtonKind Kind;
public:
virtual void Click() { Buttonbar->DoAction(this Kind); };
};
void MyDBTableButtonBarWidget::DoAction(MyDBTableButtonBarButtonKind Kind)
{
switch (Kind)
{
case MyDBTableButtonBarButtonKind::GoFirst:
this.GoFirst();
break;
case MyDBTableButtonBarButtonKind::GoLast:
this.GoLast();
break;
}
}
In this example, there is a widget control that is a bar composed of buttons, the buttonbar is referenced to a D.B. table, and has several buttons for a specific action,
like select the first record of the table, edit, move to the next.
In order to do so, each button class has friend access to private & protected methods, of the given control. As previous answer in this post, usually friend classes act a single class, decomposed in several smaller classes.
It's not a finished example, its only a general idea.

Related

External lib friend function

I am using wgetch function from curses.h and want to call e.g wgetch(handle) where handle is private member of my class. Is there any way to do it without defining new friend function of my class (like below) or maybe making it method somehow?
class foo {
WINDOW *handle;
public:
friend int wgetch(foo &t) { wgetch(t.handle); };
}
Access to private data is restricted to the class implementation and friends (use friends only when necessary). So, no, as long as handle is private, there are no options for accessing it other than friends and members.
That being said, the access does not necessarily have to be in the function you are trying to write. If there is a real reason for not defining a wgetch member of your class, maybe you could define a member that returns the value of handle (read-only public access). This seems less convenient for the users of your class though.
Given that handle is private, then the only access to it is from your class's members and its friends.
The code you have (which passes an instance of foo to a friend function) is convoluted and unconventional compared to simply having a member function:
class foo {
WINDOW *handle;
public:
int wgetch() { return ::wgetch(handle); }
};
It appears that you're writing a C++ wrapper for a Curses WINDOW*, so many small forwarding members would appear to be the natural approach. Note that we need the scoping operator :: to disambiguate the wgetch that we intend to call.
You probably ought to be aware that NCurses does include its own C++ wrappers. Although these are undocumented, we see that the definition of NCursesWindow::getch() looks exactly like the method above (see cursesw.h, line 953):
int getch() { return ::wgetch(w); }
You might save yourself a lot of work by using these classes.

virtual overloading vs `std::function` member?

I'm in a situation where I have a class, let's call it Generic. This class has members and attributes, and I plan to use it in a std::vector<Generic> or similar, processing several instances of this class.
Also, I want to specialize this class, the only difference between the generic and specialized objects would be a private method, which does not access any member of the class (but is called by other methods). My first idea was to simply declare it virtual and overload it in specialized classes like this:
class Generic
{
// all other members and attributes
private:
virtual float specialFunc(float x) const =0;
};
class Specialized_one : public Generic
{
private:
virtual float specialFunc(float x) const{ return x;}
};
class Specialized_two : public Generic
{
private:
virtual float specialFunc(float x) const{ return 2*x; }
}
And thus I guess I would have to use a std::vector<Generic*>, and create and destroy the objects dynamically.
A friend suggested me using a std::function<> attribute for my Generic class, and give the specialFunc as an argument to the constructor but I am not sure how to do it properly.
What would be the advantages and drawbacks of these two approaches, and are there other (better ?) ways to do the same thing ? I'm quite curious about it.
For the details, the specialization of each object I instantiate would be determined at runtime, depending on user input. And I might end up with a lot of these objects (not yet sure how many), so I would like to avoid any unnecessary overhead.
virtual functions and overloading model an is-a relationship while std::function models a has-a relationship.
Which one to use depends on your specific use case.
Using std::function is perhaps more flexible as you can easily modify the functionality without introducing new types.
Performance should not be the main decision point here unless this code is provably (i.e. you measured it) the tight loop bottleneck in your program.
First of all, let's throw performance out the window.
If you use virtual functions, as you stated, you may end up with a lot of classes with the same interface:
class generic {
virtual f(float x);
};
class spec1 : public generic {
virtual f(float x);
};
class spec2 : public generic {
virtual f(float x);
};
Using std::function<void(float)> as a member would allow you to avoid all the specializations:
class meaningful_class_name {
std::function<void(float)> f;
public:
meaningful_class_name(std::function<void(float)> const& p_f) : f(p_f) {}
};
In fact, if this is the ONLY thing you're using the class for, you might as well just remove it, and use a std::function<void(float)> at the level of the caller.
Advantages of std::function:
1) Less code (1 class for N functions, whereas the virtual method requires N classes for N functions. I'm making the assumption that this function is the only thing that's going to differ between classes).
2) Much more flexibility (You can pass in capturing lambdas that hold state if you want to).
3) If you write the class as a template, you could use it for all kinds of function signatures if needed.
Using std::function solves whatever problem you're attempting to tackle with virtual functions, and it seems to do it better. However, I'm not going to assert that std::function will always be better than a bunch of virtual functions in several classes. Sometimes, these functions have to be private and virtual because their implementation has nothing to do with any outside callers, so flexibility is NOT an advantage.
Disadvantages of std::function:
1) I was about to write that you can't access the private members of the generic class, but then I realized that you can modify the std::function in the class itself with a capturing lambda that holds this. Given the way you outlined the class however, this shouldn't be a problem since it seems to be oblivious to any sort of internal state.
What would be the advantages and drawbacks of these two approaches, and are there other (better ?) ways to do the same thing ?
The issue I can see is "how do you want your class defined?" (as in, what is the public interface?)
Consider creating an API like this:
class Generic
{
// all other members and attributes
explicit Generic(std::function<float(float)> specialFunc);
};
Now, you can create any instance of Generic, without care. If you have no idea what you will place in specialFunc, this is the best alternative ("you have no idea" means that clients of your code may decide in one month to place a function from another library there, an identical function ("receive x, return x"), accessing some database for the value, passing a stateful functor into your function, or whatever else).
Also, if the specialFunc can change for an existing instance (i.e. create instance with specialFunc, use it, change specialFunc, use it again, etc) you should use this variant.
This variant may be imposed on your code base by other constraints. (for example, if want to avoid making Generic virtual, or if you need it to be final for other reasons).
If (on the other hand) your specialFunc can only be a choice from a limited number of implementations, and client code cannot decide later they want something else - i.e. you only have identical function and doubling the value - like in your example - then you should rely on specializations, like in the code in your question.
TLDR: Decide based on the usage scenarios of your class.
Edit: regarding beter (or at least alternative) ways to do this ... You could inject the specialFunc in your class on an "per needed" basis:
That is, instead of this:
class Generic
{
public:
Generic(std::function<float(float> f) : specialFunc{f} {}
void fancy_computation2() { 2 * specialFunc(2.); }
void fancy_computation4() { 4 * specialFunc(4.); }
private:
std::function<float(float> specialFunc;
};
You could write this:
class Generic
{
public:
Generic() {}
void fancy_computation2(std::function<float(float> f) { 2 * f(2.); }
void fancy_computation4(std::function<float(float> f) { 4 * f(4.); }
private:
};
This offers you more flexibility (you can use different special functions with single instance), at the cost of more complicated client code. This may also be a level of flexibility that you do not want (too much).

Testing private class member in C++ without friend [duplicate]

This question already has answers here:
How do I test a class that has private methods, fields or inner classes?
(58 answers)
Closed 5 years ago.
Today I had a discussion with a colleague on whether to test or not to test private members or private state in the class. He almost convinced me why it makes sense. This question does not aim to duplicate already existing StackOverflow questions about the nature and reason of testing private members, like: What is wrong with making a unit test a friend of the class it is testing?
Colleagues suggestion was in my opinion a bit fragile to introduce the friend declaration to the unit test implementation class. In my opinion this is a no-go, because we introduce some dependency of tested code to the test code, whereas test code already depends on tested code => cyclic dependency. Even such innocent things like renaming a test class results in breaking unit tests and enforces code changes in tested code.
I'd like to ask C++ gurus to judge on the other proposal, which relies on the fact that we are allowed to specialize a template function. Just imagine the class:
// tested_class.h
struct tested_class
{
tested_class(int i) : i_(i) {}
//some function which do complex things with i
// and sometimes return a result
private:
int i_;
};
I don't like the idea to have a getter for i_ just to make it testable. So my proposal is 'test_backdoor' function template declaration in the class:
// tested_class.h
struct tested_class
{
explicit
tested_class(int i=0) : i_(i) {}
template<class Ctx>
static void test_backdoor(Ctx& ctx);
//some function which do complex things with i
// and sometimes return a result
private:
int i_;
};
By adding just this function we can make the class' private members testable. Note, there is no dependency to unit test classes, nor the template function implementation. In this example the unit test implementation uses Boost Test framework.
// tested_class_test.cpp
namespace
{
struct ctor_test_context
{
tested_class& tc_;
int expected_i;
};
}
// specialize the template member to do the rest of the test
template<>
void tested_class::test_backdoor<ctor_test_context>(ctor_test_context& ctx)
{
BOOST_REQUIRE_EQUAL(ctx.expected_i, tc_.i_);
}
BOOST_AUTO_TEST_CASE(tested_class_default_ctor)
{
tested_class tc;
ctor_test_context ctx = { tc, 0 };
tested_class::test_backdoor(ctx);
}
BOOST_AUTO_TEST_CASE(tested_class_value_init_ctor)
{
tested_class tc(-5);
ctor_test_context ctx = { tc, -5 };
tested_class::test_backdoor(ctx);
}
By introducing just a single template declaration, which is not callable at all, we give the test implementer a possibility to forward test logic into a function. The function, acts on type safe contexts and is only visible from inside the particular test compilation unit, due to anonymous type nature of test context. And the best thing is, we can define as many anonymous test contexts as we like and specialize tests on them, without ever touching the tested class.
Sure, the users must know what template specialization is, but is this code really bad or weird or unreadable? Or can I expect from C++ developers to have the knowledge what C++ template specialization is and how it works?
Elaborating on using friend to declare unit test class I don't think this is robust. Imagine boost framework (or may be other test frameworks). It generates for every test case a separate type. But why should I care as long I can write:
BOOST_AUTO_TEST_CASE(tested_class_value_init_ctor)
{
...
}
If using friends, I had to declare each test case as a friend then... Or end up introducing some test functionality in some common type (like fixture), declare it as a friend, and forward all test calls to that type... Isn't that weird?
I would like to see your pro and cons practicing this approach.
I think unit testing is about testing the observable behavior of the class under test. Therefore there is no need to test private parts as they themselves are not observable. The way you test it is by testing whether the object behaves the way you expect it (which implicitly implies that all private internal states are in order).
The reason for not to be concerned about the private parts is that this way you can change the implementation (e.g. refactoring), without having to rewrite your tests.
So my answer is don't do it (even if technically possible to) as it goes against the philosophy of unit tests.
Pros
You can access the private members to test them
Its a fairly minimal amount of hack
Cons
Broken encapsulation
Broken encapsulation that is more complicated and just as brittle as friend
Mixing test with production code by putting test_backdoor on the production side
Maintance problem ( just like friending the the test code, you've created an extremely tight coupling with your test code )
All of the Pros/Cons aside, I think you are best off making some architectural changes that allow better testing of whatever complex stuff is happening.
Possible Solutions
Use the Pimpl idiom, put the complex code in the pimpl along with the private member, and write a test for the Pimpl. The Pimpl can be forward declared as a public member, allowing external instantiation in the unit test. The Pimpl can consist of only public members, making it easier to test
Disadvantage: Lots of code
Disadvantage: opaque type that can be more difficult to see inside of when debugging
Just test the public/protected interface of the class. Test the contract that your interface lays out.
Disadvantage: unit tests are difficult/impossible to write in an isolated manner.
Similar to the Pimpl solutions, but create a free function with the complex code in it. Put the declaration in a private header ( not part of the libraries public interface ), and test it.
Break encapsulation via friend a test method/fixture
Possible variation on this: declare friend struct test_context;, put your test code inside of methods in the implementation of struct test_context. This way you don't have to friend each test case, method, or fixture. This should reduce the likelyhood of someone breaking the friending.
Break encapsulation via template specialization
What will follow is not technically speaking a straight answer to your
question as it will still make use of the "friend" functionality
but it does not require modification of the tested entity itself
and I think it addesses the concern of breaking the encapsulation
mentioned in some of the other answers; it does though require
writing some boilerplate code.
The idea behind it is not mine and the implementation is
entirely based on a trick presented and explained by litb on his
blog(coupled with this Sutter's gotw for just a little bit
more context, at least for me) - in short CRTP, friends, ADL and pointers to members
(I must confess that to my dismay the ADL part I still don't
get it entirely, but I'm relentesly working in figuring it out 100%).
I tested it with gcc 4.6, clang 3.1 and VS2010 compilers and it
works perfectly.
/* test_tag.h */
#ifndef TEST_TAG_H_INCLUDED_
#define TEST_TAG_H_INCLUDED_
template <typename Tag, typename Tag::type M>
struct Rob
{
friend typename Tag::type get(Tag)
{
return M;
}
};
template <typename Tag, typename Member>
struct TagBase
{
typedef Member type;
friend type get(Tag);
};
#endif /* TEST_TAG_H_INCLUDED_ */
/* tested_class.h */
#ifndef TESTED_CLASS_H_INCLUDED_
#define TESTED_CLASS_H_INCLUDED_
#include <string>
struct tested_class
{
tested_class(int i, const char* descr) : i_(i), descr_(descr) { }
private:
int i_;
std::string descr_;
};
/* with or without the macros or even in a different file */
# ifdef TESTING_ENABLED
# include "test_tag.h"
struct tested_class_i : TagBase<tested_class_i, int tested_class::*> { };
struct tested_class_descr : TagBase<tested_class_descr, const std::string tested_class::*> { };
template struct Rob<tested_class_i, &tested_class::i_>;
template struct Rob<tested_class_descr, &tested_class::descr_>;
# endif
#endif /* TESTED_CLASS_H_INCLUDED_ */
/* test_access.cpp */
#include "tested_class.h"
#include <cstdlib>
#include <iostream>
#include <sstream>
#define STRINGIZE0(text) #text
#define STRINGIZE(text) STRINGIZE0(text)
int assert_handler(const char* expr, const char* theFile, int theLine)
{
std::stringstream message;
message << "Assertion " << expr << " failed in " << theFile << " at line " << theLine;
message << "." << std::endl;
std::cerr << message.str();
return 1;
}
#define ASSERT_HALT() exit(__LINE__)
#define ASSERT_EQUALS(lhs, rhs) ((void)(!((lhs) == (rhs)) && assert_handler(STRINGIZE((lhs == rhs)), __FILE__, __LINE__) && (ASSERT_HALT(), 1)))
int main()
{
tested_class foo(35, "Some foo!");
// the bind pointer to member by object reference could
// be further wrapped in some "nice" macros
std::cout << " Class guts: " << foo.*get(tested_class_i()) << " - " << foo.*get(tested_class_descr()) << std::endl;
ASSERT_EQUALS(35, foo.*get(tested_class_i()));
ASSERT_EQUALS("Some foo!", foo.*get(tested_class_descr()));
ASSERT_EQUALS(80, foo.*get(tested_class_i()));
return 0;
}
I am sorry to advice this, but it helped me when most methods in those answers are not achievable without strong refactoring: add before the header for the file with the class whose private members you wish to access,
#define private public
It is evil, but
doesn't interfere with production code
does not break encapsulation as friend / changing access level does
avoids heavy refactoring with PIMPL idiom
so you may go for it...
Testing private members is not always about verifying the state by checking if it equals some expected values. In order to accommodate other, more intricate test scenarios, I sometimes use the following approach (simplified here to convey the main idea):
// Public header
struct IFoo
{
public:
virtual ~IFoo() { }
virtual void DoSomething() = 0;
};
std::shared_ptr<IFoo> CreateFoo();
// Private test header
struct IFooInternal : public IFoo
{
public:
virtual ~IFooInternal() { }
virtual void DoSomethingPrivate() = 0;
};
// Implementation header
class Foo : public IFooInternal
{
public:
virtual DoSomething();
virtual void DoSomethingPrivate();
};
// Test code
std::shared_ptr<IFooInternal> p =
std::dynamic_pointer_cast<IFooInternal>(CreateFoo());
p->DoSomethingPrivate();
This approach has the distinct advantage of promoting good design and not being messy with friend declarations. Of course, you don't have to go through the trouble most of the time because being able to test private members is a pretty nonstandard requirement to begin with.
I don't usually feel the need to unit test private members and functions. I might prefer to introduce a public function just to verify correct internal state.
But if I do decide to go poking around in the details, I use a nasty quick hack in the unit test program:
#include <system-header>
#include <system-header>
// Include ALL system headers that test-class-header might include.
// Since this is an invasive unit test that is fiddling with internal detail
// that it probably should not, this is not a hardship.
#define private public
#include "test-class-header.hpp"
...
On Linux at least this works because the C++ name mangling does not include the private/public state. I am told that on other systems this may not be true and it wouldn't link.
I used a function to test private class members which was just called TestInvariant().
It was a private member of the class and, in debug mode, was called at the beginning and end of every function (except the beginning of the ctor and end of the dctor).
It was virtual and any base class called the parent version before it's own.
That allowed me to verify the internal state of the class all of the time without exposing the intenals of the class to anyone. I had very simple tests but there is no reason why you could not have complicated ones, or even set it on or off with a flag etc.
Also you can have public Test functions which can be called by other classes which call your TestInvariant() function. Therefore when you need to change inner class workings you do not need to change any user code.
Would this help?
I think the first thing to ask is: Why is friend considered to be something that must be used with caution?
Because it breaks encapsulation. It provides another class or function with access to the internals of your object, thus expanding the visible scope of your private members. If you have a lot of friends, it's much harder to reason about the state of your object.
In my opinion, the template solution is even worse than friend in that regard. Your main stated benefit of the template is that you no longer need to explicitly friend the test from the class. I argue that, on the contrary, this is a detriment. There are two reasons for that.
The test is coupled to the internals of your class. Anyone changing the class should know that by changing the privates of the object that they may be breaking the test. friend tells them exactly what objects might be coupled to the internal state of your class, but the template solution doesn't.
Friend limits the scope expansion of your privates. If you friend a class, you know that only that class may access your internals. Thus, if you friend the test, you know that only the test can read or write to private member variables. Your template back door, however, could be used anywhere.
The template solution is ineffective because it hides the problem rather than fixing it. The underlying issue with the cyclic dependency still exists: someone changing the class must know about every use of the back door, and someone changing the test must know about the class. Basically, the reference to the test from the class was removed only by making all private data into public data in a roundabout way.
If you must access private members from your test, just friend the test fixture and be done with it. It's simple and understandable.
There's a theory that if it's private it shouldn't be tested alone, if it needs so then it should be redesigned.
For me that's Shi'ism.
On some project people create a macro for private methods, just like:
class Something{
PRIVATE:
int m_attr;
};
When compiling for test PRIVATE is defined as public, otherwise it's defined as private. that simple.

Copying Methods from Member

I have a simple, low-level container class that is used by a more high-level file class. Basically, the file class uses the container to store modifications locally before saving a final version to an actual file. Some of the methods, therefore, carry directly over from the container class to the file class. (For example, Resize().)
I've just been defining the methods in the file class to call their container class variants. For example:
void FileClass::Foo()
{
ContainerMember.Foo();
}
This is, however, growing to be a nuisance. Is there a better way to do this?
Here's a simplified example:
class MyContainer
{
// ...
public:
void Foo()
{
// This function directly handles the object's
// member variables.
}
}
class MyClass
{
MyContainer Member;
public:
void Foo()
{
Member.Foo();
// This seems to be pointless re-implementation, and it's
// inconvenient to keep MyContainer's methods and MyClass's
// wrappers for those methods synchronized.
}
}
Well, why not just inherit privatly from MyContainer and expose those functions that you want to just forward with a using declaration? That is called "Implementing MyClass in terms of MyContainer.
class MyContainer
{
public:
void Foo()
{
// This function directly handles the object's
// member variables.
}
void Bar(){
// ...
}
}
class MyClass : private MyContainer
{
public:
using MyContainer::Foo;
// would hide MyContainer::Bar
void Bar(){
// ...
MyContainer::Bar();
// ...
}
}
Now the "outside" will be able to directly call Foo, while Bar is only accessible inside of MyClass. If you now make a function with the same name, it hides the base function and you can wrap base functions like that. Of course, you now need to fully qualify the call to the base function, or you'll go into an endless recursion.
Additionally, if you want to allow (non-polymorphical) subclassing of MyClass, than this is one of the rare places, were protected inheritence is actually useful:
class MyClass : protected MyContainer{
// all stays the same, subclasses are also allowed to call the MyContainer functions
};
Non-polymorphical if your MyClass has no virtual destructor.
Yes, maintaining a proxy class like this is very annoying. Your IDE might have some tools to make it a little easier. Or you might be able to download an IDE add-on.
But it isn't usually very difficult unless you need to support dozens of functions and overrides and templates.
I usually write them like:
void Foo() { return Member.Foo(); }
int Bar(int x) { return Member.Bar(x); }
It's nice and symmetrical. C++ lets you return void values in void functions because that makes templates work better. But you can use the same thing to make other code prettier.
That's delegation inheritance and I don't know that C++ offers any mechanism to help with that.
Consider what makes sense in your case - composition (has a) or inheritance (is a) relationship between MyClass and MyContainer.
If you don't want to have code like this anymore, you are pretty much restricted to implementation inheritance (MyContainer as a base/abstract base class). However you have to make sure this actually makes sense in your application, and you are not inheriting purely for the implementation (inheritance for implementation is bad).
If in doubt, what you have is probably fine.
EDIT: I'm more used to thinking in Java/C# and overlooked the fact that C++ has the greater inheritance flexibility Xeo utilizes in his answer. That just feels like nice solution in this case.
This feature that you need to write large amounts of code is actually necessary feature. C++ is verbose language, and if you try to avoid writing code with c++, your design will never be very good.
But the real problem with this question is that the class has no behaviour. It's just a wrapper which does nothing. Every class needs to do something other than just pass data around.
The key thing is that every class has correct interface. This requirement makes it necessary to write forwarding functions. The main purpose of each member function is to distribute the work required to all data members. If you only have one data member, and you've not decided yet what the class is supposed to do, then all you have is forwarding functions. Once you add more member objects and decide what the class is supposed to do, then your forwarding functions will change to something more reasonable.
One thing which will help with this is to keep your classes small. If the interface is small, each proxy class will only have small interface and the interface will not change very often.

Keeping part of public nested class visible only to the nesting class

I have a nested class in c++ which has to be public. But I need some of its methods visible to the outer world, and the rest visible only to the nesting class. That is:
class set {
public:
class iterator {
innerMethod();
public:
outerMethod();
}
}
I want to be able to write a method for set which uses innerMethod(). If I make it public, I can access it from outside as well, which is something that I definitely don't want. Is there a way to do it without doing the "friend class set" thing?
Thanks in advance!
There is NO GOOD WAY you can do this, without using friend keyword.
In the comment you said:
In the programming class I currently
take, using 'friend' was said to be
ill-advised and generally considered
"bad programming" for the most part,
unless there is really no other way
around it. So I try to avoid it as
much as possible.
friend breaks encapsulation, maybe that is the reason why your class teacher said it's bad-programming. But member-functions too break encapsulation, then why do you use them? Why not avoid them too? friend breaks encapsulation in the same way as do member-functions; so if you're comfortable using member-functions when they're needed, then you should be comfortable using friend also when they're needed. Both exist in C++ for a reason!
class set {
public:
class iterator
{
friend class set; //<---- this gives your class set to access to inner methods!
void innerMethod(){}
public:
void outerMethod(){}
};
iterator it;
void fun()
{
it.innerMethod();
it.outerMethod();
}
};
See this : How Non-Member Functions Improve Encapsulation
No, I don't think there are other non-hacky methods but using the friend-directive.
friend exists right for this kind of purpose, why would you avoid it?
Try asking: is there any way to add 2 numbers without adding them?
Sorry if I'm harsh, but friend class is for exactly that...
Yes there is.
I've been trying to advocate the method for a while now, the basic idea is to use a Key class.
While this does not actually remove the use of friend, it does reduce the set of exposed implementations details.
class set;
// 1. Define the Key class
class set_key: noncopyable { friend class set; set_key() {} ~set_key() {} };
class set
{
// 2. Define the iterator
class iterator
{
public:
void public_method();
void restricted_method(set_key&);
}; // class iterator
}; // class set
Now, restricted_method is public, so set does not need any special access to iterator. However the use of it is restricted to those able to pass a set_key instance... and conveniently only set may build such an object.
Note that set may actually pass a set_key object to someone else it trusts. It is a key in the traditional sense: if you give a key of your flat to someone, it may entrust it to another person. However because of the semantics of the key class (non copyable, only set may construct and destroy it) this is normally limited to the duration of the scope of the key object.
Note that a evil hack is always possible, namely *((set_key*)0). This scheme protects from Murphy, not Machiavelli (it's impossible in C++ anyway).
You can do something like this:
class set
{
public:
class iterator
{
protected:
iterator(){};
virtual ~iterator(){};
public:
//outer world methods...
};
private:
class privateIterator : public iterator
{
public:
privateIterator(){};
~privateIterator(){}
//inner methods;
};
public:
iterator* CreateIterator()
{
return new privateIterator();//this is used to be sure that you only create private iterator instances
}
};
I don't know if it's the right answer, but it does now uses friend key work and it hides some of the methods. The only problem is that you can't declare privateIterator and you always must use CreateIterator to create an instance...