I have a class that has some members (data and functions) that I do not want
to be public. However, I do want these private members to be accessible to
objects of the same class.
Example
=======
A a, b; // 'a' and 'b' are objects of the same class
C c; // 'c' is not
c = a.p(); // No; 'p' is private
b = a.p(); // Okay; 'b' belongs to the same class as 'a'
Is there a way to do this in C++? If the syntax does not allow it, is there
a suitable design pattern?
I think I know what you're asking. I wrote up a bit of mock code that
might demonstrate one way to do this. My idea is to create a nested
private class and overload the assignment operator so that you can
make this assignment:
b = a.p(); But not this one:
c = a.p();
This doesn't make A:
() a private member, but you do have two other
things going for you. Obviously it can only be called from an A
object, and now it's return value can only be accepted by an A object.
Here's what I came up with:
#ifndef EXAMPLE_HPP
#define EXAMPLE_HPP
class Example
{
private:
// Inner class that is used to pass
// data from Example object to Example
// object.
class DataWrapper
{
public:
int _x;
DataWrapper(int x)
{
_x = x;
}
};
public:
Example(int exampleX);
Example& operator=(const DataWrapper& data);
DataWrapper p(int x);
int exampleX() { return _exampleX; }
private:
int _exampleX;
};
Example::Example(int exampleX)
{
_exampleX = exampleX;
}
Example:
ataWrapper Example:
(int x)
{
return DataWrapper(x);
}
Example& Example:
perator=(const DataWrapper& data)
{
_exampleX = data._x;
return *this;
}
#endif
And then there's this bit of code to demonstrate it:
#include <iostream>
using namespace std;
#include "Example.hpp"
class OtherExample
{
public:
// This line creates a compiler error.
// ! void print(const Example:
ataWrapper& data) {}
};
int main(int argc, char *argv[])
{
Example test(5), test2(10);
test = test2.p(50);
cout << test.exampleX() << endl;
// One possible pitfall: You can use this method
// to gain access to the public members of the
// private nested class.
int z = test.p(10)._x;
cout << z << endl;
return 0;
}
I'm sure there are ways to improve this, but it's at least something.
Does that help?