Reference in place of getters? - c++

in C++ is it a bad practice to use reference in place of getters?
for example:
class X
{
int mP;
public:
const int& P;
X():P(mP){}
};
and later
X xl;
int h = xl.P;

Just think about refactoring to make the access thread safe, that won't work well this way and require a lot of changes in the client classes/functions.
If you have class members, that are guaranteed not to be changed over lifetime of the instance, you can simply provide const int P; and initialize it properly in your class' constructors.
If the value is to be visible class wide use a static const int P;
In any other case use a public getter:
int P() const; // a return type of 'const int &' would be redundant
1st shot implementation:
int X::P() const
{
return mP;
}
Thread safe implementation:
class X {
{
// ...
private:
// ...
mutable std::mutex internalDataGuard;
};
int X::P() const
{
std::lock(internalDataGuard);
return mP;
}

None of this is good:
class X { public: int x; };
class X {
private: int m_x;
public: const int& get() const { return m_x; }
public: void set(const int& other) { m_x = other; }
};
class X {
private: int m_x;
public: const int& x() const { return m_x; }
public: void x(const int& other) { m_x = other; }
};
class X {
private: int m_x;
public: const int& x() const { return m_x; }
public: int& x() { return m_x; }
};
Pick one, it's a design decision.
Having 'const int& x' to publish the private member will work:
class X {
private: int m_x;
public: const int& x;
public: X() : m_x(0), x(m_x) {}
// Take care for copy and assignment
};
The cost is a larger memory footprint.

Related

How to instantiate abstract child class with parent class

I'm trying to make a Chess game, and I'm having difficulties with creating the objects. My thought process went something like this:
Create a game board with 64 tiles, the tiles would have their own position and a pointer to a piece, thus I would be able to "easily" load in and unload a piece.
Tile class:
class Tile {
private:
int x;
int y;
Piece* piece;
public:
Tile(int x, int y) {
this->x = x;
this->y = y;
piece = nullptr;
}
void loadTile(Piece piece) {
this->piece = new Piece(piece); //this gives an error
}
void unloadTile() {
delete this->piece;
}
};
The individual pieces would then inherit from a parent class (below you can see a dumbed-down version). Inherited pieces would all have the same constructor and they would only differ in the way they calculate the possible moves. This, in my mind, is the best scenario to use a virtual function.
Piece and pawn class:
class Piece {
protected:
int x;
int y;
public:
Piece(int x, int y) {
this->x = x;
this->y = y;
}
virtual vector<int> returnPossibleMoves() = 0;
};
class Pawn : public Piece {
public:
using Piece::Piece;
vector<int> returnPossibleMoves() {
vector<int> moves;
moves.push_back(10); //dont think about this too much
return moves;
}
};
And here is the problem - the loadTile() function cannot instantiate the piece object because it is abstract.
I can see that my code may not work because I try to instantiate Piece with Pawn, but I don't really know how I would make it work, or what the workaround for this is. Hopefully you will be able to see what I'm trying to go for.
To strictly answer the question: you cannot create instances of abstract classes. That's why new Piece is not allowed. You would have to create an instance of a derived type that is not abstract, such as Pawn, and assign the piece pointer to point to that:
void Tile::loadTile() {
this->piece = new Pawn; //this is allowed
}
There are clearly some design changes that you'll need to make with this in mind, some of which have been mentioned in the comments on your question.
The Tile don't know which Piece type to instantiate, this is the fundamental problem.
What about something like this? (Disclaim, I just implemented some ideas, the code need probably lot of improvements until to get to sufficient quality)
#include <array>
#include <cassert>
#include <memory>
#include <vector>
using namespace std;
class Piece;
using CPiecePtr = std::shared_ptr<const Piece>;
enum class PieceType
{
Pawn
};
class Pos
{
int m_x=0;
int m_y=0;
public:
Pos()=default;
Pos(const Pos&)=default;
Pos& operator=(const Pos&)=default;
Pos( int x, int y): m_x(x), m_y(y)
{
assert(x>=0 && x<8 && y>=0 && y<8);
}
int x() const { return m_x; }
int y() const { return m_y; }
};
class Move
{
Pos m_origin;
Pos m_destination;
public:
Move()=default;
Move(const Move&)=default;
Move& operator=(const Move&)=default;
Move( const Pos& orig, const Pos& dest): m_origin(orig), m_destination(dest){}
const Pos& getDestination() const { return m_destination; }
const Pos& getOrigin() const { return m_origin; }
};
using MoveSet = std::vector<Move>;
class Tile
{
private:
CPiecePtr m_piece;
public:
void loadTile(CPiecePtr piece)
{
m_piece = piece;
}
void unloadTile()
{
m_piece = nullptr;
}
void setPiece(CPiecePtr piece) // this is more generic than previous two functions
{
m_piece = piece;
}
CPiecePtr getPiece() const
{
return m_piece;
}
};
class Piece
{
PieceType m_type;
public:
virtual MoveSet returnPossibleMoves(const Pos&) const = 0;
Piece(): m_type(PieceType::Pawn){}
PieceType getType() const { return m_type; }
};
class Pawn : public Piece
{
public:
MoveSet returnPossibleMoves(const Pos& pos) const override
{
MoveSet moves;
moves.push_back(Move(pos, Pos(pos.x(), pos.y()+1)));
//...
//TODO how to manage special moves? King-rook, replace pawn at end line...
return moves;
}
};
class Chess
{
private:
std::array<std::array<Tile,8>,8> m_board;
std::vector<CPiecePtr> m_pieces;
public:
Chess()
{
m_pieces.push_back( std::make_shared<const Pawn>());
//...
setPieceAt(Pos(0,1), m_pieces[0]);
}
CPiecePtr getPieceAt( const Pos& pos) const
{
return m_board[pos.x()][pos.y()].getPiece();
}
void setPieceAt( const Pos& pos, CPiecePtr piece)
{
return m_board[pos.x()][pos.y()].setPiece(piece);
}
// example:
MoveSet getMoveSetForPos( const Pos& pos)
{
const auto& piecePtr = getPieceAt(pos);
if (nullptr != piecePtr)
{
return piecePtr->returnPossibleMoves(pos);
}
return {};
}
void movePiece( const Move& move)
{
const auto& prevPiece = getPieceAt(move.getOrigin());
const auto& nextPiece = getPieceAt(move.getDestination());
assert(prevPiece && !nextPiece);
setPieceAt(move.getDestination(), prevPiece);
setPieceAt(move.getOrigin(), nullptr);
}
};
int main()
{
Chess chess;
const auto& moves = chess.getMoveSetForPos(Pos(0,1));
if (moves.size()>0)
{
chess.movePiece(moves[0]);
}
assert( chess.getPieceAt(Pos(0,2))->getType() == PieceType::Pawn);
return 0;
}
EDIT: I was not very proud of the answer, so I edited the code to make it compile. However, a fully working Chess is more complex than that, I leave how to manage king-rook and other special moves to the reader.

Friend class read only access C++ [duplicate]

Whoopee, not working on that socket library for the moment. I'm trying to educate myself a little more in C++.
With classes, is there a way to make a variable read-only to the public, but read+write when accessed privately? e.g. something like this:
class myClass {
private:
int x; // this could be any type, hypothetically
public:
void f() {
x = 10; // this is OK
}
}
int main() {
myClass temp;
// I want this, but with private: it's not allowed
cout << temp.x << endl;
// this is what I want:
// this to be allowed
temp.f(); // this sets x...
// this to be allowed
int myint = temp.x;
// this NOT to be allowed
temp.x = myint;
}
My question, condensed, is how to allow full access to x from within f() but read-only access from anywhere else, i.e. int newint = temp.x; allowed, but temp.x = 5; not allowed? like a const variable, but writable from f()...
EDIT: I forgot to mention that I plan to be returning a large vector instance, using a getX() function would only make a copy of that and it isn't really optimal. I could return a pointer to it, but that's bad practice iirc.
P.S.: Where would I post if I just want to basically show my knowledge of pointers and ask if it's complete or not? Thanks!
Of course you can:
class MyClass
{
int x_;
public:
int x() const { return x_; }
};
If you don't want to make a copy (for integers, there is no overhead), do the following:
class MyClass
{
std::vector<double> v_;
public:
decltype(v)& v() const { return v_; }
};
or with C++98:
class MyClass
{
std::vector<double> v_;
public:
const std::vector<double>& v() const { return v_; }
};
This does not make any copy. It returns a reference to const.
While I think a getter function that returns const T& is the better solution, you can have almost precisely the syntax you asked for:
class myClass {
private:
int x_; // Note: different name than public, read-only interface
public:
void f() {
x_ = 10; // Note use of private var
}
const int& x;
myClass() : x_(42), x(x_) {} // must have constructor to initialize reference
};
int main() {
myClass temp;
// temp.x is const, so ...
cout << temp.x << endl; // works
// temp.x = 57; // fails
}
EDIT: With a proxy class, you can get precisely the syntax you asked for:
class myClass {
public:
template <class T>
class proxy {
friend class myClass;
private:
T data;
T operator=(const T& arg) { data = arg; return data; }
public:
operator const T&() const { return data; }
};
proxy<int> x;
// proxy<std::vector<double> > y;
public:
void f() {
x = 10; // Note use of private var
}
};
temp.x appears to be a read-write int in the class, but a read-only int in main.
A simple solution, like Rob's, but without constructor:
class myClass {
private:
int m_x = 10; // Note: name modified from read-only reference in public interface
public:
const int& x = m_x;
};
int main() {
myClass temp;
cout << temp.x << endl; //works.
//temp.x = 57; //fails.
}
It is more like get method, but shorter.
Constant pointer is simple, and should work at all types you can make pointer to.
This may do what you want.
If you want a readonly variable but don't want the client to have to change the way they access it, try this templated class:
template<typename MemberOfWhichClass, typename primative>
class ReadOnly {
friend MemberOfWhichClass;
public:
inline operator primative() const { return x; }
template<typename number> inline bool operator==(const number& y) const { return x == y; }
template<typename number> inline number operator+ (const number& y) const { return x + y; }
template<typename number> inline number operator- (const number& y) const { return x - y; }
template<typename number> inline number operator* (const number& y) const { return x * y; }
template<typename number> inline number operator/ (const number& y) const { return x / y; }
template<typename number> inline number operator<<(const number& y) const { return x <<y; }
template<typename number> inline number operator>>(const number& y) const { return x >> y; }
template<typename number> inline number operator^ (const number& y) const { return x ^ y; }
template<typename number> inline number operator| (const number& y) const { return x | y; }
template<typename number> inline number operator& (const number& y) const { return x & y; }
template<typename number> inline number operator&&(const number& y) const { return x &&y; }
template<typename number> inline number operator||(const number& y) const { return x ||y; }
template<typename number> inline number operator~() const { return ~x; }
protected:
template<typename number> inline number operator= (const number& y) { return x = y; }
template<typename number> inline number operator+=(const number& y) { return x += y; }
template<typename number> inline number operator-=(const number& y) { return x -= y; }
template<typename number> inline number operator*=(const number& y) { return x *= y; }
template<typename number> inline number operator/=(const number& y) { return x /= y; }
template<typename number> inline number operator&=(const number& y) { return x &= y; }
template<typename number> inline number operator|=(const number& y) { return x |= y; }
primative x;
};
Example Use:
class Foo {
public:
ReadOnly<Foo, int> x;
};
Now you can access Foo.x, but you can't change Foo.x!
Remember you'll need to add bitwise and unary operators as well! This is just an example to get you started
You may want to mimic C# properties for access (depending what you're going for, intended environment, etc.).
class Foo
{
private:
int bar;
public:
__declspec( property( get = Getter ) ) int Bar;
void Getter() const
{
return bar;
}
}
There is a way to do it with a member variable, but it is probably not the advisable way of doing it.
Have a private member that is writable, and a const reference public member variable that aliases a member of its own class.
class Foo
{
private:
Bar private_bar;
public:
const Bar& readonly_bar; // must appear after private_bar
// in the class definition
Foo() :
readonly_bar( private_bar )
{
}
};
That will give you what you want.
void Foo::someNonConstmethod()
{
private_bar.modifyTo( value );
}
void freeMethod()
{
readonly_bar.getSomeAttribute();
}
What you can do, and what you should do are different matters. I'm not sure the method I just outlined is popular and would pass many code reviews. It also unnecessarily increases sizeof(Foo) (albeit by a small amount) whereas a simple accessor "getter" would not, and can be inlined, so it won't generate more code either.
You would have to leave it private and then make a function to access the value;
private:
int x;
public:
int X()
{
return x;
}
As mentioned in other answers, you can create read only functionality for a class member by making it private and defining a getter function but no setter. But that's a lot of work to do for every class member.
You can also use macros to generate getter functions automatically:
#define get_trick(...) get_
#define readonly(type, name) \
private: type name; \
public: type get_trick()name() {\
return name;\
}
Then you can make the class this way:
class myClass {
readonly(int, x)
}
which expands to
class myClass {
private: int x;
public: int get_x() {
return x;
}
}
You need to make the member private and provide a public getter method.
The only way I know of granting read-only access to private data members in a c++ class is to have a public function. In your case, it will like:
int getx() const { return x; }
or
int x() const { return x; }.
By making a data member private you are by default making it invisible (a.k.a no access) to the scope outside of the class. In essence, the members of the class have read/write access to the private data member (assuming you are not specifying it to be const). friends of the class get access to the private data members.
Refer here and/or any good C++ book on access specifiers.
Write a public getter function.
int getX(){ return x; }
I had a similiar problem. Here is my solution:
enum access_type{readonly, read_and_write};
template<access_type access>
class software_parameter;
template<>
class software_parameter<read_and_write>{
protected:
static unsigned int test_data;
};
template<>
class software_parameter<readonly> : public software_parameter<read_and_write>{
public:
static const unsigned int & test_data;
};
class read_and_write_access_manager : public software_parameter<read_and_write>{
friend class example_class_with_write_permission;
};
class example_class_with_write_permission{
public:
void set_value(unsigned int value);
};
And the .cpp file:
unsigned int software_parameter<read_and_write>::test_data=1;
const unsigned int & software_parameter<readonly>::test_data=software_parameter<read_and_write>::test_data;
void example_class_with_write_permission::set_value(unsigned int value){software_parameter<read_and_write>::test_data=value;};
The idea is, that everyone can read the software parameter, but only the friends of the class read_and_write_access_manager are allowed to change software parameter.
but temp.x = 5; not allowed?
This is any how not allowed in the snippet posted because it is anyhow declared as private and can be accessed in the class scope only.
Here are asking for accessing
cout << temp.x << endl;
but here not for-
int myint = temp.x;
This sounds very contradictory.

How to validate input parameters in C++ constructor?

Following example shows the crux of the problem. I need to initialize const members of a class. This can only be done in the initializer-list and not in constructor body. I want to assert or throw an error if input to the constructor is invalid, that is, if the vector size is less than 3.
class A {
// In following constructor, how do we make sure if params.size()
// is at least 3.
A(const std::vector<int>& params):
x(params[0]), y(params[1]), z(params[2]) {}
private:
const int x;
const int y;
const int z;
};
Please advise how to achieve this in Modern C++ (11 and later)
Just add a layer of abstraction. You can write a function that makes sure the vector is of the correct size and you can even make sure the values are in an expected range, if you have one. That would look like
class A {
A(const std::vector<int>& params):
x(verify(params, 0)), y(verify(params, 1)), z(verify(params, 3)) {}
private:
static int verify(const std::vector<int>& params, int index)
{
if (params.size() < 4) // or use if (params.size() <= index) if you only care if the index will work
throw something;
return params[index];
}
const int x;
const int y;
const int z;
};
const members can only be initialized in the constructors's member initialization list. To validate the caller's input, you would have to call a helper function to validate each input value before passing it to the corresponding member, eg:
int check(const std::vector<int> &params, int index) {
if (params.size() <= index) throw std::length_error("");
return params[index];
}
class A {
A(const std::vector<int>& params):
x(check(params, 0)), y(check(params, 1)), z(check(params, 3)) {}
private:
const int x;
const int y;
const int z;
};
Or, simply utilize the vector's own built-in bounds checking instead:
class A {
A(const std::vector<int>& params):
x(params.at(0)), y(params.at(1)), z(params.at(3)) {}
private:
const int x;
const int y;
const int z;
};
Not as elegant as other solutions but... you can simply add a throw in a ternary operator inside the initialization of the first constant
class A
{
private:
const int x;
const int y;
const int z;
public:
A (const std::vector<int>& params)
: x{ params.size() < 4u ? throw std::runtime_error{"!"}
: params[0] },
y{params[1]}, z{params[3]}
{ }
};
Off Topic suggestion: if A is a class, maybe it's better that the constructor is public.
Other option extra layer through conversion:
class A_params{
friend class A;
int x;
int y;
int z;
void validate();
public:
A_params(std::initializer_list<int>);
A_params(const std::vector<int>&);
A_params(int(&)[3]);
//...
};
class A {
// In following constructor, how do we make sure if params.size()
// is at least 3.
public:
A(A_params params):
x(params.x), y(params.y), z(params.z) {}
private:
const int x;
const int y;
const int z;
};

Declaring readonly variables on a C++ class or struct

I'm coming to C++ from C# and const-correctness is still new to me. In C# I could declare a property like this:
class Type
{
public readonly int x;
public Type(int y)
{
x = y;
}
}
This would ensure that x was only set during initialization. I would like to do something similar in C++. The best I can come up with though is:
class Type
{
private:
int _x;
public:
Type(int y) { _x = y; }
int get_x() { return _x; }
};
Is there a better way to do this? Even better: Can I do this with a struct? The type I have in mind is really just a collection of data, with no logic, so a struct would be better if I could guarantee that its values are set only during initialization.
There is a const modifier:
class Type
{
private:
const int _x;
int j;
public:
Type(int y):_x(y) { j = 5; }
int get_x() { return _x; }
// disable changing the object through assignment
Type& operator=(const Type&) = delete;
};
Note that you need to initialize constant in the constructor initialization list. Other variables you can also initialize in the constructor body.
About your second question, yes, you can do something like this:
struct Type
{
const int x;
const int y;
Type(int vx, int vy): x(vx), y(vy){}
// disable changing the object through assignment
Type& operator=(const Type&) = delete;
};
Rather than a collection of constants, you could have a constant collection. The property of being constant seems to pertain to your use case, not the data model itself. Like so:
struct extent { int width; int height; };
const extent e { 20, 30 };
It's possible to have specifically constant data members of a class, but then you need to write a constructor to initialize it:
struct Foo
{
const int x;
int & y;
int z;
Foo(int a, int & b) : x(a + b), y(b), z(b - a) { }
};
(The example also shows another type of data member that needs to be initialized: references.)
Of course, structs and classes are the same thing.
You can initialize class const members with constructor. If you need add some other logic in constructor, but in .cpp file not in .h, you can create a private method and call it in constructor.
File.h
class Example
{
private:
const int constantMember1;
const int constantMember2;
const int constantMember3;
void Init();
public:
Example(int a, int b) :constantMember1(a), constantMember2(b), constantMember3(a + b) {
//Initialization
Init();
};
};
File.cpp
void Init()
{
//Some Logic intialization
}
This is not exactly answering the question asked, but if you wanted to have the simplicity of directly accessing member variables in a struct without getters, but wanted to ensure that nobody could modify the values, you could do something like this:
#include <iostream>
using namespace std;
class TypeFriend;
struct Type
{
const int &x;
const int y;
Type (int vx, int vy):x (_x), y (vy), _x (vx)
{
}
private:
friend class TypeFriend;
int _x;
};
struct TypeFriend
{
TypeFriend (Type & t):_t (t)
{
}
void setX (int newX)
{
_t._x = newX;
}
private:
Type & _t;
};
int main ()
{
Type t (1, 2);
TypeFriend tf (t);
cout << t.x << "," << t.y << endl;
// t.x = 6; // error: assignment of read-only location ‘t.Type::x’
// cout<<t.x << ","<<t.y<<endl;
tf.setX (5);
cout << t.x << "," << t.y << endl;
return 0;
}
The result of running this is:
1,2
5,2
Type::x cannot be modified externally, so it is read-only, but via TypeFriend it can be changed. This can be useful if you wanted to expose a simple interface of direct member access for reading, but wanted to restrict how those members could be changed.

Class variables: public access read-only, but private access read/write

Whoopee, not working on that socket library for the moment. I'm trying to educate myself a little more in C++.
With classes, is there a way to make a variable read-only to the public, but read+write when accessed privately? e.g. something like this:
class myClass {
private:
int x; // this could be any type, hypothetically
public:
void f() {
x = 10; // this is OK
}
}
int main() {
myClass temp;
// I want this, but with private: it's not allowed
cout << temp.x << endl;
// this is what I want:
// this to be allowed
temp.f(); // this sets x...
// this to be allowed
int myint = temp.x;
// this NOT to be allowed
temp.x = myint;
}
My question, condensed, is how to allow full access to x from within f() but read-only access from anywhere else, i.e. int newint = temp.x; allowed, but temp.x = 5; not allowed? like a const variable, but writable from f()...
EDIT: I forgot to mention that I plan to be returning a large vector instance, using a getX() function would only make a copy of that and it isn't really optimal. I could return a pointer to it, but that's bad practice iirc.
P.S.: Where would I post if I just want to basically show my knowledge of pointers and ask if it's complete or not? Thanks!
Of course you can:
class MyClass
{
int x_;
public:
int x() const { return x_; }
};
If you don't want to make a copy (for integers, there is no overhead), do the following:
class MyClass
{
std::vector<double> v_;
public:
decltype(v)& v() const { return v_; }
};
or with C++98:
class MyClass
{
std::vector<double> v_;
public:
const std::vector<double>& v() const { return v_; }
};
This does not make any copy. It returns a reference to const.
While I think a getter function that returns const T& is the better solution, you can have almost precisely the syntax you asked for:
class myClass {
private:
int x_; // Note: different name than public, read-only interface
public:
void f() {
x_ = 10; // Note use of private var
}
const int& x;
myClass() : x_(42), x(x_) {} // must have constructor to initialize reference
};
int main() {
myClass temp;
// temp.x is const, so ...
cout << temp.x << endl; // works
// temp.x = 57; // fails
}
EDIT: With a proxy class, you can get precisely the syntax you asked for:
class myClass {
public:
template <class T>
class proxy {
friend class myClass;
private:
T data;
T operator=(const T& arg) { data = arg; return data; }
public:
operator const T&() const { return data; }
};
proxy<int> x;
// proxy<std::vector<double> > y;
public:
void f() {
x = 10; // Note use of private var
}
};
temp.x appears to be a read-write int in the class, but a read-only int in main.
A simple solution, like Rob's, but without constructor:
class myClass {
private:
int m_x = 10; // Note: name modified from read-only reference in public interface
public:
const int& x = m_x;
};
int main() {
myClass temp;
cout << temp.x << endl; //works.
//temp.x = 57; //fails.
}
It is more like get method, but shorter.
Constant pointer is simple, and should work at all types you can make pointer to.
This may do what you want.
If you want a readonly variable but don't want the client to have to change the way they access it, try this templated class:
template<typename MemberOfWhichClass, typename primative>
class ReadOnly {
friend MemberOfWhichClass;
public:
inline operator primative() const { return x; }
template<typename number> inline bool operator==(const number& y) const { return x == y; }
template<typename number> inline number operator+ (const number& y) const { return x + y; }
template<typename number> inline number operator- (const number& y) const { return x - y; }
template<typename number> inline number operator* (const number& y) const { return x * y; }
template<typename number> inline number operator/ (const number& y) const { return x / y; }
template<typename number> inline number operator<<(const number& y) const { return x <<y; }
template<typename number> inline number operator>>(const number& y) const { return x >> y; }
template<typename number> inline number operator^ (const number& y) const { return x ^ y; }
template<typename number> inline number operator| (const number& y) const { return x | y; }
template<typename number> inline number operator& (const number& y) const { return x & y; }
template<typename number> inline number operator&&(const number& y) const { return x &&y; }
template<typename number> inline number operator||(const number& y) const { return x ||y; }
template<typename number> inline number operator~() const { return ~x; }
protected:
template<typename number> inline number operator= (const number& y) { return x = y; }
template<typename number> inline number operator+=(const number& y) { return x += y; }
template<typename number> inline number operator-=(const number& y) { return x -= y; }
template<typename number> inline number operator*=(const number& y) { return x *= y; }
template<typename number> inline number operator/=(const number& y) { return x /= y; }
template<typename number> inline number operator&=(const number& y) { return x &= y; }
template<typename number> inline number operator|=(const number& y) { return x |= y; }
primative x;
};
Example Use:
class Foo {
public:
ReadOnly<Foo, int> x;
};
Now you can access Foo.x, but you can't change Foo.x!
Remember you'll need to add bitwise and unary operators as well! This is just an example to get you started
You may want to mimic C# properties for access (depending what you're going for, intended environment, etc.).
class Foo
{
private:
int bar;
public:
__declspec( property( get = Getter ) ) int Bar;
void Getter() const
{
return bar;
}
}
There is a way to do it with a member variable, but it is probably not the advisable way of doing it.
Have a private member that is writable, and a const reference public member variable that aliases a member of its own class.
class Foo
{
private:
Bar private_bar;
public:
const Bar& readonly_bar; // must appear after private_bar
// in the class definition
Foo() :
readonly_bar( private_bar )
{
}
};
That will give you what you want.
void Foo::someNonConstmethod()
{
private_bar.modifyTo( value );
}
void freeMethod()
{
readonly_bar.getSomeAttribute();
}
What you can do, and what you should do are different matters. I'm not sure the method I just outlined is popular and would pass many code reviews. It also unnecessarily increases sizeof(Foo) (albeit by a small amount) whereas a simple accessor "getter" would not, and can be inlined, so it won't generate more code either.
You would have to leave it private and then make a function to access the value;
private:
int x;
public:
int X()
{
return x;
}
As mentioned in other answers, you can create read only functionality for a class member by making it private and defining a getter function but no setter. But that's a lot of work to do for every class member.
You can also use macros to generate getter functions automatically:
#define get_trick(...) get_
#define readonly(type, name) \
private: type name; \
public: type get_trick()name() {\
return name;\
}
Then you can make the class this way:
class myClass {
readonly(int, x)
}
which expands to
class myClass {
private: int x;
public: int get_x() {
return x;
}
}
You need to make the member private and provide a public getter method.
The only way I know of granting read-only access to private data members in a c++ class is to have a public function. In your case, it will like:
int getx() const { return x; }
or
int x() const { return x; }.
By making a data member private you are by default making it invisible (a.k.a no access) to the scope outside of the class. In essence, the members of the class have read/write access to the private data member (assuming you are not specifying it to be const). friends of the class get access to the private data members.
Refer here and/or any good C++ book on access specifiers.
Write a public getter function.
int getX(){ return x; }
I had a similiar problem. Here is my solution:
enum access_type{readonly, read_and_write};
template<access_type access>
class software_parameter;
template<>
class software_parameter<read_and_write>{
protected:
static unsigned int test_data;
};
template<>
class software_parameter<readonly> : public software_parameter<read_and_write>{
public:
static const unsigned int & test_data;
};
class read_and_write_access_manager : public software_parameter<read_and_write>{
friend class example_class_with_write_permission;
};
class example_class_with_write_permission{
public:
void set_value(unsigned int value);
};
And the .cpp file:
unsigned int software_parameter<read_and_write>::test_data=1;
const unsigned int & software_parameter<readonly>::test_data=software_parameter<read_and_write>::test_data;
void example_class_with_write_permission::set_value(unsigned int value){software_parameter<read_and_write>::test_data=value;};
The idea is, that everyone can read the software parameter, but only the friends of the class read_and_write_access_manager are allowed to change software parameter.
but temp.x = 5; not allowed?
This is any how not allowed in the snippet posted because it is anyhow declared as private and can be accessed in the class scope only.
Here are asking for accessing
cout << temp.x << endl;
but here not for-
int myint = temp.x;
This sounds very contradictory.