Access C++ class member object, but do not allow to override it -
i'm learning c++ , have small problem. have class contains vector<int>. outside vector<int> should accessable, should possible add/remove/get elements.
it should not possible override object new instance. here such example class (it's minimalized):
class myclass { public: vector<int>& vec() { return _vec; } private: vector<int> _vec; }; e.g. following code works:
myclass x; x.vec().push_back(0); x.vec().push_back(7); x.vec().push_back(9); cout << c.vec().size() << endl; but unfortunately following code works:
myclass x; x.vec() = vector<int>(); i disallow this, did find solution return pointer of type vector<int> *. learned pointers 'evil' , shouldn't use them directly, have use smart pointers. think problem smart pointer useless, don't know how solve simple problem:-/
or simple pointer cleanest solution?
best regards
kevin
-edit-
in general make can used follwing c# class:
public class myclass { public list<int> list { get; private set; } public myclass() { list = new list<int>(); } } it's example , thought how make in c++. maybe cases have more complex classes vector<int>/list<int> include other classes.
but maybe possible defining own methods (=interface) internal object.
it seems wrong me acceptable solution provide forwarding functions potentially methods in vector class. propose alternative answer.
create small template class publically derived vector hides operator= method making private.
template<class t> class immutablevector : public vector<t> { private: immutablevector &operator=(vector<t>); }; then in myclass, wherever have used vector, use immutablevector instead.
class myclass { public: immutablevector<int>& vec() { return _vec; } private: immutablevector<int> _vec; }; now can safely access vector functionality via vec method, won't able assign new vector instance.
Comments
Post a Comment