I've always wondered is there a way to have a class member without using getters that can only be modified by it's class?
What I'm thinking of is something like this.
class A
{
public:
crazyconst int x;
void doStuff()
{
// Gettin' stuff done
x = someValue; // OK
}
};
int main(int argc, char** argv)
{
A a;
a.x = 4; // ERROR
}
So it's visible, but read-only for everyone beside its class.
Your class could have a public const reference to a private, non-const data member.
Edit: However, I should point out that doing this would prevent you from using the compiler-generated copy constructor and copy assignment operator.
The answer is no you can't do this without a getter of some sort. However, you can make the getter reusable and you can make the simple syntax of a field work (mostly), without parentheses.
(C++11 required)
template<typename Friend, typename FieldType>
class crazyconst
{
FieldType value;
friend Friend;
FieldType& operator=(const FieldType& newValue) { return value = newValue; }
public:
operator FieldType(void) const { return value; }
FieldType operator()(void) const { return value; }
};
class A
{
public:
crazyconst<A, int> x;
void doStuff()
{
// Gettin' stuff done
x = 5; // OK
}
};
int main(int argc, char** argv)
{
A a;
int b = a.x;
int c = a.x(); // also works
}
C++03 version: http://ideone.com/8T1Po
But beware, this will compile but not work as expected:
const int& the_x = a.x;
a.doStuff();
std::cout << the_x;
OTOH, this should be fine:
const auto& ref_x = a.x;
a.doStuff();
std::cout << ref_x;
Related
Is there a way to use templates to create a standard constructor of class in your main?
If I have a class:
myclass.h
class myClass
{
private:
float a;
public:
myClass(float _a) {a = _a;}
float getA(){return a;}
~myClass() {}
};
Is there a way to template this in your main like so:
main.cpp
#include "myclass.h"
typedef myClass<5.0> Dummy
int main(int argc, char const *argv[])
{
// EDIT: removed the following typo
// Dummy dummy();
Dummy dummy;
std::cout << dummy.getA() << std::endl;
return 0;
}
Which should output:
> 5.0000000
So that one may define in the main a standard way to construct the instances.
C++17 and Below
Unfortunately C++ does not allow you to use floating point types as non-type template parameters yet. That said, you can fake it by accepting a numerator and denominator as integers and then doing that "math" in the class to get a floating point value. That would look like
template<size_t numerator, size_t denominator = 1> // use a default value so you don't have to specify the denominator for whole values
class myClass
{
private:
float a;
public:
myClass(float _a = static_cast<float>(numerator) / denominator) : a(_a) {}
float getA(){return a;}
~myClass() {}
};
typedef myClass<5> Dummy;
int main(int argc, char const *argv[])
{
Dummy dummy; // notice this isn't Dummy dummy();. That makes a function, not a variable
std::cout << dummy.getA() << std::endl;
return 0;
}
You could also add a default value to numerator if you want to so that you could do
// Pre C++17
myClass<> foo;
//C++17 and later
myClass foo;
C++20
Now that we can use floating point types1 the code can be simplified to:
template<float default_value = 0.0f>
class myClass
{
private:
float a;
public:
myClass(float _a = default_value) : a(_a) {}
float getA(){return a;}
~myClass() {}
};
typedef myClass<5.0f> Dummy;
int main(int argc, char const *argv[])
{
Dummy dummy;
std::cout << dummy.getA() << std::endl;
return 0;
}
1: no compilers actually support this yet, but it is allowed per the standard
Building onto #pptaszni's answer, you could create a "factory factory function":
auto makeMyClassFactory(float value) {
return [=] {
return myClass{value};
};
}
auto const Dummy = makeMyClassFactory(5.0f);
int main(int argc, char const *argv[])
{
auto dummy = Dummy();
std::cout << dummy.getA() << std::endl;
return 0;
}
See it live on Wandbox
You are possibly better off just using a default instance which you make copies of whenever you need a new instance:
#include "myclass.h"
Dummy myClass(5.0);
int main(int argc, char const *argv[])
{
myClass dummy1 = Dummy;
std::cout << dummy1.getA() << std::endl;
myClass dummy2 = Dummy;
std::cout << dummy2.getA() << std::endl;
return 0;
}
Not really, but you can write a factory function (or class if it is more complicated) like this:
myClass createMyClassV5()
{
return myClass(5.0);
}
Unfortunately, you cannot make it a template, because float are not allowed to be template non-type parameters. You could do it with int though.
Is there any possible way to overload operator* in such way that it's assigning and observing functions are defined apart?
class my_class
{
private:
int value;
public:
int& operator*(){return value;}
};
int main()
{
my_class obj;
int val = 56;
*obj = val; // assign
val = *obj; // observe, same operator* is called
}
Sort of -- you can have the operator* return an instance of another class, rather than returning a reference directly. The instance of the other class then defines both a conversion operator and an assignment operator.
(In your sample code, it looks like you've overloaded the multiplication operator when you meant to overload the dereferencing operator; I'll use the dereferencing operator below.)
For example:
class my_class
{
friend class my_class_ref;
public:
my_class_ref operator*() { return my_class_ref(this); }
private:
int value;
};
class my_class_ref
{
public:
operator int() { return owner->value; } // "observe"
my_class_ref& operator=(int new_value) { owner->value = new_value; return *this; } // "assign"
private:
my_class* owner;
my_class_ref(my_class* owner) { this->owner = owner; }
};
There are some caveats. For example, as my_class_ref is implemented with a pointer to its parent class, your code must be careful that my_class_ref always has a lifetime shorter than the lifetime of the corresponding my_class -- otherwise you will dereference an invalid pointer.
In practice, if you pretend that my_class_ref doesn't exist (i.e. never declare a variable with that class) it can work very well.
Write your class like so
class my_class
{
private:
int value;
public:
int operator*() const { // observing
return value;
}
int& operator*() { // assigning
return value;
}
};
Then these operators are dissambiguated by constness, so code like this is possible
int _tmain(int argc, _TCHAR* argv[])
{
my_class a;
*a = 1; // assigning
int k = *(const_cast<my_class const&>(a)); // observing
return 0;
}
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 c {
private:
int n[10];
public:
c();
~c();
int operator()(int i) { return n[i];};
};
class cc {
private:
public:
c *mass;
cc();
~cc();
c& operator*() const {return *mass;};
};
int somfunc() {
c *c1 = new c();
cc * cc1 = new cc();
(*cc1->mass)(1);
delete c1;
}
I've got a pointer into class cc to class c.
Is there any way to get rid of record like this:
(*cc1->mass)(1);
and write somethink like that:
cc1->mass(1);
is it impossible?
When I saw the tags "c++" and "operator overloading", my mind alarm turns ON.
C++ operator overloading is complex, and some operators like "()" or "->" make it more difficult.
I suggest, before overloading operators, making either a global function or method with the same purpouse, test it works, and later replace it with the operator.
Global friend function example:
class c {
private:
int n[10];
public:
c();
~c();
// int operator()(int i) { return n[i]; }
// there is a friend global function, that when receives a "c" object,
// as a parameter, or declares a "c" object, as a local variable,
// this function, will have access to the "public" members of "c" objects,
// the "thisref" will be removed, when turned into a method
friend int c_subscript(c thisref, int i) ;
};
int c_subscript(c* thisref, int i)
{
return c->n[i];
}
int main()
{
c* objC() = new c();
// do something with "objcC"
int x = c_subscript(objC, 3);
// do something with "x"
return 0;
} // int main(...)
Local function ( "method" ) example:
class c {
private:
int n[10];
public:
c();
~c();
// int operator()(int i) { return n[i]; }
int subscript(int i) ;
};
int c::subscript(int i)
{
return this.n[i];
}
int main()
{
c* objC() = new c();
// do something with "objcC"
int x = c->subscript(objC, 3);
// do something with "x"
return 0;
} // int main(...)
And, finally use the overloaded operator:
class c {
private:
int n[10];
public:
c();
~c();
int subscript(int i) ;
int operator()(int i) { return this.subscript(i); }
};
int c::subscript(int i)
{
return this.n[i];
}
int main()
{
c* objC() = new c();
// do something with "objcC"
int x = c->subscript(3);
// do something with "x"
int x = c(3);
// do something with "x"
return 0;
} // int main(...)
Note that in the final example, I keep the method with a unique identifier.
Cheers.
Could always do this:
class cc {
private:
c *_mass;
public:
c& mass() const {return *_mass;};
};
Now..
cc1->mass()(1);
If mass were an object, not a pointer, you could use the syntax you want:
class cc {
private:
public:
c mass;
cc();
~cc();
const c& operator*() const {return mass;};
};
…
cc1->mass(1);
You can with
(*(*cc1))(1)
because operator() is applied to an object, not a pointer.
You can use
(**cc1)(1);
Or
cc1->mass->operator()(1);
I would like someone to explain me the "name::name" syntax and how it is used on C++ programming. I have been looking through but I don't get it yet. Thanks for help.
Here is context code:
void UsbProSender::SendMessageHeader(byte label, int size) const {
Serial.write(0x7E);
Serial.write(label);
Serial.write(size);
Serial.write(size >> 8);
}
:: is the scope resolution operator.
std::cout is the name cout in the namespace std.
std::vector::push_back is the push_back method of std::vector.
In your code example:
void UsbProSender::SendMessageHeader(byte label, int size) const {
Serial.write(0x7E);
Serial.write(label);
Serial.write(size);
Serial.write(size >> 8);
}
UsbProSender::SendMessageHeader is providing the definition for the SendMessageHeader method of the UsbProSender class.
Another (more complete) example:
class Bar {
int foo(int i); // forward declaration
};
// the definition
int Bar::foo(int i) {
return i;
}
It is operator for scope resolution.
Consider that code
class A { public: void f(){} };
class B { public: void f(){} };
class C : public A, public B {};
int main(int argc, char *argv[])
{
C c;
// c.f(); // ambiguous: which one of two f() is called?
c.A::f(); // OK
c.B::f(); // OK
return 0;
}