Unit test private methods by making them free functions - c++

In the 2017 cppcon videos, I came across a talk by Klaus Iglberger which was entitled "Free Your Functions!".
In this talk, the speaker talked about how switching to free functions could
easy up the process of testing private methods (See at 19:00). The idea is that you pull the
private method out of the class (you make it a free function) and it becomes testable.
At first, I found the idea interesting, but then the
more I thought about it, the less I understood how this is actually supposed to work. For example,
let's say I have the following (dummy) class:
class SomeClass
{
public:
SomeClass();
~SomeClass();
void someTask();
private:
void someComplexTask();
void someOtherComplexTask();
};
void SomeClass::someTask()
{
someComplexTask();
someOtherComplexTask();
}
// private tasks implementations...
Then someComplexTask() and someOtherComplexTask() are private methods. This means that they
are implementation details, i.e. that they can only be called inside SomeClass (or friends). It
seems to me that if you make them free functions, yes they become testable, but they are no longer
private, nor a mere implementation detail specific to SomeClass. In fact, they can be called from anywhere in the code...
So my question is: why is Mr. Iglberger's point valid?

This is a clear indication that you have a design flaw. If you have a
private function that you need to test and you have to bend backwards
to make it work then something is wrong. You have missed something.
Your design doesn't work.
His point is not to just make private functions free. He is not saying: "get all your private functions and make them free functions". He is saying that functionality that needs to be tested shouldn't be an implementation detail because if you need to test it that is an indication the functionality is useful.
Please pay close attention to the transformation he does to the code:
initial code:
class X
{
public:
void doSomething( ... ) {
...
resetValues();
...
}
...
private:
void resetValues() {
for( int& value : values_ )
value = 0;
}
std::vector<int> values_;
};
He pulls resetValues out of X but it makes it operate on a std::vector<T>, not on X:
void resetValues( std::vector<int>& vec )
{
for( int& value : vec )
value = 0;
}
Now resetValues is a functionality that can be reused and tested. As it truly has nothing to do with X, but with resetting all values of a vector it is a valid design to make it a free function instead of a private X method.
I like how Rann Lifshitz put it in his comment:
I think the better way to go here is to understand that some private
functions are, in fact, common utility functions

I have watched the video too. But, I have a few disagreements.
1- Does your method require accessing fields? If not, it does not belong to the class. But if it does, they need the fields. The free functions do not have access to the fields unless you pass them as function arguments. Please consider that free functions should not be looked as public function.
2- Not everything is supposed to be free function. But it is a good practice to avoid putting everything in the class when they are not necessary.
3- Private function are not often supposed to be tested. But if you insist, you might be able to perform such as invalid hack (which not always works as mentioned in the comments):
#define class struct
#define private public
#define protected public
#include "library.h"
#undef class
#undef private
#undef protected
Freeing your function is neater but not more feasible.

Related

c++ internal helper class

I would like to ask question regarding internal helper class in C++. What is the best way to structure this?
Let me clarify what do I mean by internal helper class by example.
// MyClass.h
class MyClass
{
int myData;
bool isSomething;
...
public:
void DoSomething();
};
// MyClass.cpp
// This is what I mean by internal helper function. Helper function that's only visible int the implementation file (.cpp) but requires access to the private members of the class.
static void DoSomethingInternal( MyClass *myClass )
{
// Access myClass private members
}
void MyClass::DoSomething()
{
...
DoSomethingInternal(this);
...
}
I know that declaring friend function can be a solution. However, it makes the class declaration ugly. In addition, for every new helper function, I have to add a friend function.
Is there an idiom/design pattern for this? I have been searching in the Internet, but didn't find any.
Thank you in advance. Your answers are greatly appreciated.
In my experience, a lot of dev teams have no problem with static local helper functions, it helps reduce header bloat, helps keep the formally exposed interface smaller, and so forth. It has the advantage of being lightweight, it has the disadvantage that it can lead to friend bloat/pollution if you are using lots of private members and no accessors.
But within the discussion community it is generally frowned upon in favor of the following.
Declaring helpers as private member functions.
This has the advantage of clearly associating fn _doThingsForFoo(Foo*) with Foo, and saving you from a lot of headaches exposing private members.
It has the downside of basically showing your underwear to everyone who needs to #include your header.
Using the Pimpl idiom.
You declare a second class, the "Private Implementation" (https://en.wikipedia.org/wiki/Opaque_pointer, Is the pImpl idiom really used in practice?) and you put all of the private stuff you don't want in the main header into that.
It has the advantage of allowing you to hide your stuff, it has the disadvantage of adding an extra pointer to feed, store and traverse (oh and free).
There are couple of ways to accomplish that.
Use a helper class/function in the .cpp file if the helper functions don't need access to the data directly. I would recommend this method ahead of the next method.
In the .cpp file:
// Create a namespace that is unique to the file
namespace MyClassNS
{
namespace HelperAPI
{
void DoSomethingInternal(MyClass* obj) { ... }
}
}
using namespace MyClassNS;
void MyClass::DoSomething()
{
...
//
HelperAPI::DoSomethingInternal(this);
...
}
Use the pimple idiom. When using this idiom, you can add any number of helper functions in the private data class without touching the public interface of the class.
The design pattern is simple: don't use helper classes. If a class should do something, let it do it itself.
As per the upvoted answer given by StenSoft, you should implement the methods inside the class. However, if that is not an option for some reason, then use helpers. If even that is not an option, then use reflection. If even that is not an option, then use a command listener inside your class. If even that is not an option, then watch a tutorial.
You can read these following sites for this purpose PIMPL, Opaque pointer. With this you only need to have one member variable and you can put all private things into the private class.
your header:
class PrivateClass;
class Class
{
public:
// ...
private:
PrivateClass* m_Private;
};
your source:
class PrivateClass
{
// ...
};
Class::Class
: m_Private( new PrivateClass )
{
// ...
}
UPDATE: I forgot to tell mention to delete the private member in the desctructor.
Class::~Class
{
delete m_Private;
// ...
}
// ...

Free function versus member function

What is the advantage of having a free function (in anonymous namespace and accessible only in a single source file) and sending all variables as parameters as opposed to having a private class member function free of any parameters and accessing member variables directly?
header:
Class A {
int myVariable;
void DoSomething() {
myVariable = 1;
}
};
source:
namespace {
void DoSomething2(int &a) {
a = 1;
}
}
int A::SomeFunction() {
DoSomething2(myVariable); // calling free function
DoSomething(); // calling member function
}
If you prefer making them members, then what if I have a case where I first call a function that is not accessing any member variables, but that function calls another function which is accessing a member. Should they both be member functions or free?
see this question: Effective C++ Item 23 Prefer non-member non-friend functions to member functions
and also C++ Member Functions vs Free Functions
You should prefer free functions, in the extent that it promotes loose coupling.
Consider making it a member function only if it works on the guts of your class, and that you consider it really really tied to your class.
It is a point of the book 101 C++ coding standards, which states to prefer free function and static function over member functions.
Altough this may be considered opinion based, it allows to keep class little, and to seperate concerns.
This answer states: "the reason for this rule is that by using member functions you may rely too much on the internals of a class by accident."
One advantage of a non-member function in a source file is similar to the benefits of the Pimpl idiom: clients using your headers do not have to recompile if you change your implementation.
// widget.h
class Widget
{
public:
void meh();
private:
int bla_;
};
// widget.cpp
namespace {
void helper(Widget* w) // clients will never know about this
{ /* yadayada */ }
}
void widget::meh()
{ helper(this); }
Of course, when written like this, helper() can only use the public interface of Widget, so you gain little. You can put a friend declaration for helper() inside Widget but at some point you better switch to a full-blown Pimpl solution.
The primary advantage of free functions vs member functions is that it helps decouple the interface from the implementation. For example, std::sort doesn't need to know anything about the underlying container on which it operates, just that it's given access to a container (through iterators) that provide certain characteristics.
In your example the DoSomething2 method doesn't do much to decrease coupling since it still has to access the private member by having it passed by reference. It's almost certainly more obvious to just do the state mutation in the plain DoSomething method instead.
When you can implement a task or algorithm in terms of a class's public interface then that makes it a good candidate to make a free function. Scott Meyers summarizes a reasonable set of rules here: http://cpptips.com/nmemfunc_encap

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.

Vectors Classes Private/Public

In C++ is always better to keep data of a class as private members.
If a class has a vector as member is better to put it as a private or public member?
If I have a vector as private member I cannot easily access to the member function of the vector. So I have to design the class with a method for every function I need to access the vector methods?
Example given:
class MyClass{
private:
std::vector<int> _myints;
public:
get_SizeMyints(){return _myints.size();}
add_IntToMyints(int x){_myints.push_back(x));
};
or is better to keep the vector public and call MyClass._myints.push_back(x)?
---------------------edit--------------
and just for clarity for what is needed this question:
snake.h:
enum directions{UP, DOWN, RIGHT, LEFT, IN, OUT, FW, RW };
class Snake
{
private:
enum directions head_dir;
int cubes_taken;
float score;
struct_color snake_color;
V4 head_pos;
public:
std::vector<Polygon4> p_list; //the public vector which should be private...
Snake();
V4 get_head_pos();
Polygon4 create_cube(V4 point);
void initialize_snake();
void move(directions);
void set_head_dir(directions dir);
directions get_head_dir();
void sum_cubes_taken(int x);
int get_cube_taken();
void sum_score(float x);
float get_score();
void set_snake_color();
};
so now I know how to change the code.
btw... a question, if I need to copy the vector in an other class like this: GlBox.p_list = Snake.p_list (works if are private) what will be an efficent method if they where private?
Running a for cycle to copy the the elements and pusshing back them in the GLBox.p_list seems a bit inefficent to me (but may be just an impression) :(
If it doesn't matter if someone comes along and empties the vector or rearranges all it's elements, then make it public. If it matters, then yes, you should make it protected/private, and make public wrappers like you have. [Edit] Since you say "it's a snake", that means it'd be bad if someone came and removed or replaced bits. Ergo, you should make it protected or private. [/Edit]
You can simplify a lot of them:
MyClass {
private:
std::vector<int> _myints;
public:
const std::vector<int>& get_ints() const {return _myints;}
add_IntToMyints(int x){_myints.push_back(x));
};
That get_ints() function will allow someone to look at the vector all they want, but won't let them change anything. However, better practice is to encapsulate the vector entirely. This will allow you to replace the vector with a deque or list or something else later on. You can get the size with std::distance(myobj.ints_begin(), myobj.ints_end());
MyClass {
private:
std::vector<int> _myints;
public:
typedef std::vector<int>::const_iterator const_iterator;
const_iterator ints_begin() const {return _myints.begin();}
const_iterator ints_end() const {return _myints.end();}
add_IntToMyints(int x){_myints.push_back(x));
};
For good encapsulation, you should keep your vector private.
Your question is not very concrete, so here's an answer in the same spirit:
Generally, your classes should be designed to express a particular concept and functionality. They should not just hand through another member class. If you find yourself replicating all the interface functions of a member object, something is wrong.
Maybe sometimes you really just need a collection of other things. In that case, consider a plain old aggregate, or even a tuple. But if you're designing a proper class, make the interface meaningful to the task at hand, and hide the implementation. So the main question here is, why do you need to expose the vector itself? What is its role in the class? What does its emptiness signify in terms of the semantics of your class?
Find the appropriate idioms and ideas to design a minimal, modular interface for your class, and the question might just go away by itself.
(One more idea: If for example you have some range-based needs, consider exposing a template member function accepting a pair of iterators. That way you leverage the power of generic algorithms without depending on the choice of container.)
Normally, good coding practice is to keep your data members private or protected, and provide whatever public methods will be needed to access them. Not all the methods of (in this case) vector, just what will be useful for your application.
That depends on your class's purpose. If you're trying simply trying to wrap the vector and want to use it as a vector you could make an argument for making the vector public.
Generally speaking I would suggest making it private and providing an appropriate interface to manipulate the container. Additionally this lets you change the container under the hood if a different container would ever be more appropriate (as long as you don't tie your public interface to the container type).
Further as an aside, avoid names that begin with underscores as there are some such identifiers reserved for the implementation and it's safer to just avoid all of them rather than trying to remember the rules in all cases.
A point to realize is that making the std::vector private is only half of the story when it comes to good encapsulation. For example, if you have:
class MyClass {
public:
// Constructors, other member functions, etc.
int getIntAt(int index) const;
private:
std::vector<int> myInts_;
};
...then arguably, this is no better than just making myInts_ public. Either way, clients will write code using MyClass which is dependent on the fact that the underlying representation requires the use of a std::vector. This means that in the future, if you decide that a more efficient implementation would utilize a std::list instead:
class MyClass {
public:
// Constructors, other member functions, etc.
int getIntAt(int index) const; // whoops!
private:
std::list<int> myInts_;
};
...now you have a problem. Since you can't access into a std::list by index, you would either have to get rid of getIntAt, or implement getIntAt using a loop. Neither option is good; in the first case, you now have clients with code that doesn't compile. In the second case, you now have clients with code that just silently became less efficient.
This is the danger of exposing any public member functions which are specific to your choice of implementation. It's important to keep flexibility/future maintenance in mind when designing your class interface. There are a number of ways you could do this with your particular example; see Mooing Duck's answer for one such interface that exposes iterators.
Or, if you would like to maximize code readability, you could design the interface around what MyClass logically represents; in your case, a snake:
class MyClass {
public:
// Constructors, etc.
void addToHead(int value);
void addToTail(int value);
void removeFromHead();
void removeFromTail();
private:
// implementation details which the client shouldn't care about
};
This offers an abstraction of a snake object in your program, and the simplified interface gives you the flexibility to choose whatever implementation suits it best. And if the situation arises, you can always change that implementation without breaking client code.
Theoretically in Object Oriented Programming any attributes should be private and gain access to them via public methods such as Get() and Set().
I think you question is not complete, but what I understand from what you're trying to achieve you need to inherit from std::vector and extend its functionality, to both satisfy your fast access needs and not messing around with encapsulation. (Consider reading on "Inheritance" first from any C++ book, or other OO language)
Having said that, your code might look as following:
class MyClass : public std::vector<int>
{
//whatever else you need goes here
}
int main(void)
{
MyClass var;
var.push_back(3);
int size = var.size(); // size will be 1
}
Hope this answered your question

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.