Only allow access to an object's members, not the object itself - c++

Given the following class:
class Foo
{
public:
//...
private:
Bar mBar;
};
Is it possible to expose the mBar member in such a way that it's members can be accessed, but not the mBar object itself?
The reason is that users should be able to access all of mBar's members but they should not be able to assign another Bar instance to mBar.
Bar has a lot of members and it would be cumbersome to write getters/setters and forwarding fuctions for them all. But if mBar is made public one is able to do aFoo.mBar = Bar(/*...*/);which is the only thing that should not be allowed.
Deleting Bar's assignment operators is not an option.

if you only want to protect against errors and not Machiavelli, operator-> might help (you might probably want a wrapper instead of directly put it in foo though):
class Foo
{
public:
//...
const Bar* operator ->() const { return &mBar; }
Bar* operator ->() { return &mBar; }
private:
Bar mBar;
};
so
Foo foo;
foo->bar_member;
foo.foo_member;
// Machiavelli
*foo.operator->() = Bar();

I would probably rethink your design but here is a possible indirect way using an intermediate get method:
struct Bar {
int intAttr;
};
class Foo {
Bar mBar;
public:
template <class U>
U& get(U Bar::* p) {
return mBar.*p;
}
};
This way, you can access any public member of mBar using:
Foo foo;
foo.get(&Bar::intAttr); // get
foo.get(&Bar::intAttr) = 0; // set

Related

Make a member variable object modifiable but not assignable

I've searched high and low for the answer for this, perhaps I'm just not using the right terms to get any results?
Is there any way to make it so that a member variable is const in that it can't be reassigned, and will always be the same object, but still allow the object itself to be modified? Much like the behavior of a const pointer to a non-const object, but without being an actual pointer?
The main use case that I see for this would be composition. Let's say Foo has-a Bar, and you want to be able to access and modify that Bar, but not change which Bar Foo has. Just change the properties/call non-const methods on that Bar. Is there any way to do this?
Not with const correctness machinery; it's too primitive for that (it's just a single bit: either "change" or "not change").
You can however mark assignment private and the container a friend so that only container methods will be allowed to assign, but mutators could be marked public for others to use.
class Foo {
public:
int x, y;
Foo() : x(0), y(0) {}
friend class Bar;
private:
Foo& operator=(const Foo& other){
...
return *this;
}
};
class Bar {
public:
Foo foo;
Bar(){
foo = Foo(); // OK from here
};
};
void baz() {
Bar bar;
bar.foo.x = 42; // Ok assigning a member of foo
bar.foo = Foo(); // Invalid from here (doesn't compile)
}
Normally you would just do
struct Foo {
Bar bar;
};
Each Foo object then has a Bar subobject, which is contained within Foo itself, and whose address does not change. Assigning to bar invokes Bar's assignment operator; it doesn't change the location of bar.
If you need polymorphic behaviour from the Bar, you would do
struct Foo {
const std::unique_ptr<Bar> bar;
};
Here, since the std::unique_ptr is const, it cannot be made to point to a different Bar object after Foo's initialization, but since the Bar itself is not const, it can be modified. You could also use const std::shared_ptr<Bar>.
My best guess is that you can make the member private and then use setter member functions that achieve the mechanics that you desire (i.e. the end user can only modify your member variables in the way that you want them to be modified).

Initialize static member inside constructor of an instance

I want to initialize a static member variable inside the constructor of a particular instance. Is that a bad idea?
The situation is as follows. I have a static member variable that all instances of this class should share. Normally, I'd just use a static initializer. But, I don't have the necessary information needed to construct the static object until the constructor gets called. But of course, I don't want to create a new object every time the constructor gets called, so I want to do something like this.
class Foo
{
static Bar * bar;
Foo( Xyz xyz);
};
Bar * Foo::bar = nullptr;
Foo::Foo(Xyz xyz)
{
if (Foo::bar == nullptr)
{
// initialize static bar
Foo::bar = new Bar(xyz);
}
}
I know of course xyz migth be different for different calls to the constructor of Foo. That doesn't matter for me.
Is this bad software design? I feel a little weird initializing a static object inside the constructor. But it's not that different from the singleton design pattern. So maybe it is ok?
EDIT
Thanks for the comments guys. It seems like people are not a fan of this design. I will modify it so that I create a Bar once before the very first instantiation of Foo, and pass a Bar * as a parameter in Foo's constructor. Each Foo will have a pointer to a Bar, and I'll make sure all Foos are all pointing to the same Bar. Is that better?
Is this bad software design?
In general it would be considered so, yes. There are many reasons why the Singleton Pattern or having static variables in this way is considered bad design.
But it's not that different from the singleton design pattern. So maybe it is ok?
If you really want to make that a Singleton Pattern you should rather use Scott Meyer's technique:
class Foo
{
static Bar* bar(Xyz xyz) {
static Bar barInstance(xyz);
return &barInstance;
}
Foo( Xyz xyz) : xyz_(xyz) {}
void baz() {
Bar* b = bar(xyz_);
// use b ...
}
private:
Xyz xyz_;
};
This code will be thread safe, and avoids the need to check for a nullptr.
Though Bar should make up a Singleton on it's own then, and you use it in Foo whenever needed:
class Bar {
public:
static Bar& getInstance(Xyz xyz) {
static Bar barInstance(xyz);
return &barInstance;
}
private:
Bar(Xyz xyz) : xyz_(Xyz) {}
Bar(const Bar&) delete;
Bar(Bar&&) delete;
Bar& operator=(const Bar&) delete;
Bar& operator=(Bar&) delete;
Xyz xyz_;
};
class Foo {
public:
Foo(Xyz xyz) barRef(Bar::getInstance(xyz)) {
// ^^^ Notice 1st instance of Foo created
// wins to create the Bar actually
}
private:
Bar& barRef;
};

How to properly initialize non-default-constructible class member?

Assume I define a class Foo, which does not implement a default constructor.
In addition, I have a class Bar, which "owns" an instance of Foo:
class Foo() {
private:
int m_member;
public:
Foo( int value ) : m_member(value) { }
};
class Bar() {
private:
Foo m_foo;
public:
Bar( /* ... */ ) {
int something;
/* lots of code to determine 'something' */
/* should initialize m_foo to 'Foo(something)' here */
}
};
The code as shown won't run, since Bar is trying to call the default constructor of Foo.
Now what I am trying to do is to have the constructor of Bar first determine something and then pass the result to the constructor of Foo.
One way to solve this is to have Bar only own a reference/pointer to Foo and initialize it after m_something was determined. However, I'd like to avoid that to make clear that the lifetime of m_foo is completely dependent on the lifetime of the owning class.
Another way would be to implement a default constructor in Foo and set the value later, which I would also like to avoid, since any instance of Foo should have a valid value for it's member (at any time).
What is the proper way to implement this? Am I stuck with a reference/pointer here?
The best idea will be to create helper function, that will calculate something and then just initialize m_foo in constructor initialized list.
class Bar {
private:
Foo m_foo;
public:
Bar( /* ... */ ) : m_foo(calculate_something()) {
}
private:
static int calculate_something()
{
int something = 0;
// lot of code to calculate something
return something;
}
};
Does this complex initialization code actually belong to Bar? It may be good to consider having a separate class to just do this initializing. Something like
class Bar {
public:
Bar(int param, Foo foo): m_foo(foo) {
// do just some very simple calculations, or use only constructor initialization list
}
...
}
class BarBuilder {
public:
BarBuilder(/*...*/) {
// do all calculations, boiling down to a few parameters for Bar and Foo
Foo foo(fooParameter);
m_result = new Bar(barParameter, foo); // give Foo here explicitly
}
Bar getResult() { return *m_result; }
private:
Bar* m_result; // or better use unique_ptr
}
This also opens the way to a full Builder pattern that might be useful in case, for example, you do not always need all that complex calculations.
This assumes all classes to be copy-constructible, but you may more-or-less easily modify it to support what you need.

Creating objects only as shared pointers through a base class 'create'-method

I am trying to achieve that certain objects within my application can only be constructed as shared_ptr's by a call to a static method called "create".
Of course I could do this by directly adding the static 'create' method to all the respective class. However, this would mean I have to repeat very similar code in almost all my classes. A macro would work, but I do not find this very elegant.
I came up with an alternative way of doing this by deriving all classes from a templated 'BaseObject' class that implements the 'create' method and returns the pointer. This almost works, except that std::make_shared cannot access the constructor of its child class when it is protected.
The non-solution would be to make the child class constructor public (see (1) in the example below). But now Foo can be normally constructed again and this would defeat the entire point. An alternative solution would be to friend BaseObject in the child class and make use of shared_ptr directly (see (2) in the example).
Both solutions put extra burden on the implementer of the child class. Since they have to either find an alternative way of making the constructor non-public or put a friend declaration. The (2) solution has the additional problem of not being able to use the more efficient make_shared.
My question: is there a better way of doing this?
template<class T>
class BaseObject
{
public:
typedef std::shared_ptr<T> SharedPtr;
template<class... Args>
static typename BaseObject<T>::SharedPtr create(Args&&... args)
{
return std::make_shared<T>(args...);
//return std::shared_ptr<T>(new T(args...)); (2)
}
};
class Foo : public BaseObject<Foo>
{
//friend BaseObject<Foo>; (2)
protected: //public (1)
Foo(int a = 0) : m_foo(a) {}
private:
int m_foo;
};
int main(int argc, char* argv[])
{
Foo::SharedPtr bla = Foo::create(1);
return 0;
}
Update:
They pass-key idiom seems to provide the best solution for me at this moment:
template<class T>
class BaseObject
{
public:
typedef std::shared_ptr<T> SharedPtr;
class Key
{
friend class BaseObject<T>;
Key() {}
};
template<class... Args>
static typename BaseObject<T>::SharedPtr create(Args&&... args)
{
return std::make_shared<T>(Key(), args...);
}
};
class Foo : public BaseObject<Foo>
{
public:
Foo(BaseObject<Foo>::Key, int a = 0) : m_foo(a) {}
private:
int m_foo;
};
The good things:
Only possible to create an object of Foo as a shared_ptr through
Foo::create.
No need to add complex friend declarations in Foo.
std::make_shared still works.
The only problem with this solution is the requirement to have 'Key' as a first argument in the constructor. But I can live with that.
Better is subjective, but I believe it would be a little more intuitive if you would make your constructor private, and std::make_shared a friend function. This way the only function that could create your object would be std::make_shared, and you could write
std::shared_ptr<Foo> ptr = std::make_shared<Foo>(12);
instead of:
Foo::SharedPtr bla = Foo::create(1);
So any future reader of your code would understand what you mean withou actually looking at the Foo class.
UPDATE
I have tried out what I wrote, but did not really work. Here is an answer for a similar question instead, which most likely also aplies for your question:
Using make_shared with a protected constructor + abstract interface
UPDATE 2
Here is how you can make it work (VC++2013)
#include <memory>
using namespace std;
class Foo
{
protected:
Foo(int a = 0) : m_foo(a) {}
private:
int m_foo;
friend shared_ptr<Foo> make_shared<>();
friend class _Ref_count_obj<Foo>;
};
int main()
{
shared_ptr<Foo> foo = make_shared<Foo, int>(12);
return 0;
}
_Ref_count_obj is internally used by make_shared, that's why you need to befriend that too.

Return child class into base class object

I am trying to get my head around some inheritance problem in C++:
Consider a base class Foo() with a method method() and its derived class Bar. Now I override the method in Bar.
class Foo{
public:
double method();
}
class Bar public: Foo
{
public:
double method()
}
And a function like this:
Foo get_bar(){
Bar bar()
return bar
}
Calling the function get_bar() I'd like to be able to call Bar::method()
Foo foo = get_bar();
foo.method() (-> which should be Bar::method)
Is this possible? And if, how? I think I am making a fundamental mistake here which I don't see. Thanks!
To override (not overwrite) a function, it must be virtual:
class Foo {
public:
virtual void method();
virtual ~Foo() = default; // technically optional, but usually needed
};
For completeness, here is the corrected syntax for the derived class:
class Bar : public Foo {
public:
void method() override; // override is optional, but a good idea
};
Polymorphism only works on references and pointers, so your function would have to return one of those, not a base-class object. As it is (once the syntax is fixed), it slices the Bar object to return a copy of its Foo, which would not give you the overridden function that you want.
There's no existing object to return a reference to; so you'll probably have to dynamically create one an return a pointer. Unless you enjoy long debugging sessions, use smart pointers to manage dynamic objects:
std::unique_ptr<Foo> get_bar() {
return std::unique_ptr<Foo>(new Bar); // C++14: make_unique<Bar>();
}
If I understand your question correctly you want get_bar() to return a child class Bar as if it was the base class Foo such that you can subsequently call method on it and it will call Bar::method(). Yes, you can do that. It is called Polymorphism.
In order to achieve this get_bar() needs to return a pointer otherwise you will encounter the slicing problem and won't get the polymorphic behaviour you are looking for. As get_bar() is a factory function transferring ownership to the caller it is preferable to return a smart-pointer like unique_ptr or shared_ptr:
std::unique_ptr<Foo> getBar() {
return std::make_unique<Bar>();
}
Foo::method() needs to be virtual in order to override it in Bar. And in order to destroy Bar properly when the Foo pointer is deleted Foo must have a virtual destructor:
class Foo {
public:
virtual void method();
virtual ~Foo(){}
};
class Bar : public Foo {
public:
void method() override;
};