How to write setter for class member variable? - c++

I'm trying to write a simple class in c++ with getter and setter for a class member variable. The getter works fine, but I cant write the setter. Is it possible to overwrite the "m_var" with a setter or is this only for pointer-variables possible?
class Foo: public QObject {
Q_OBJECT
public:
MyOtherClass& getVar() {
return m_var;
}
private:
MyOtherClass m_var;
};

this should be like that :
// this is your setter
// you can set the var parameter as const because it is just copied to var
void setVar(const MyOtherClass& var){m_var = var;}
//this is your getter
MyOtherClass& getVar() {return m_var;}
// also this getter should be declared as const because you return a copy
// of m_var and thus you do not modify the object
MyOtherClass getVarByCopy() const {return m_var;}
the following code compiles fine with g++ :
class A
{
public :
int someInt;
};
class B{
A m_var;
public:
void setVar(const A& var){m_var = var;}
A& getVar() {return m_var;}
};
int main(int argc, char* argv[])
{
B b;
A a;
a = b.getVar();
b.setVar(a);
return 0;
}

Are we missing something?
class Foo: ...
{
.....
.....
MyOtherClass& getVar() {
return m_var;
}
Your
getVar()
is actually a setter as it returns a non-const reference.
check this code.
class MyOtherClass
{
public:
MyOtherClass(int i=10)
{
m_someInt = i;
}
int m_someInt;
};
class QObject
{
};
class Foo: public QObject
{
// Q_OBJECT
public:
MyOtherClass& getVar()
{
return m_var;
}
private:
MyOtherClass m_var;
};
void someFunc()
{
Foo f1;
printf("%d", f1.getVar().m_someInt);
f1.getVar() = 100;
printf("\r\n %d", f1.getVar().m_someInt);
}
Though i dont like the idea of such design.
If you really want getVar() to only get but not set, then it should be
const MyOtherClass& getVar()const {
return m_var;
}

Related

Can inhereted classes be made const? [duplicate]

I would like to inherit from a class with the const specifier like this:
class Property
{
int get() const;
void set(int a);
};
class ConstChild : public const Property
{
// Can never call A::set() with this class, even if
// the instantiation of this class is not const
};
class NonConstChild : public Property
{
// Can call both A::set() and A::get() depending on
// the constness of instantiation of this class
};
My compiler obviously gives me an error for the const keyword in the second classes declaration. Ideally I'd like to avoid having to create a new class ReadOnlyProperty from which ConstChild would inherit.
Can I somehow use the const keyword for inheritance?
If not, do you have any other ideas on how to solve this problem?
Introduce mutability later in your inheritance tree and derive appropriately:
class Property
{
int get() const;
};
class MutableProperty : public Property {
{
void set(int a);
};
And then:
class ConstChild : public Property { ... };
class MutableChild : public MutableProperty { ... };
I had the need for a related problem, which is: to really control/highlight mutable and const access on some class.
I did it with this simple reusable template wrapper:
template <typename T>
class TAccessor : private T
{
public:
const T& Const() const { return *this; }
T& Mutable() { return *this; }
};
// Example of use:
template <typename T>
using MyVector = TAccessor<std::vector<T>>;
void main()
{
MyVector<int> vector;
vector.Mutable().push_back(10);
int x = vector.Const()[1];
...
}
If you create a const member function set, you will get what you need.
class Property
{
int get() const;
void set(int a);
};
class ConstChild : public Property
{
void set(int a) const {}
};
The only caveat is that a sly user can circumvent your intention by using:
ConstChild child;
child.set(10); // Not OK by the compiler
Property& base = child;
base.set(10); // OK by the compiler
I would like to inherit from a class with the const specifier"
However much you want to is irrelevant. You cannot. That is not valid C++.
Can I somehow use the const keyword for inheritance?"
No.
Use a data member or private base class instead of public base class.
Then you control the access to that member.
You can make the Property thing an abstract interface if you need polymorphic behavior.
You can use a template class and a specialization for a constant type:
template<typename T> class base_property {
protected:
T value;
};
template<typename T> class property : public base_property<T> {
public:
const T& get()const { return value; }
void set(const T& v){ value = v; }
};
template<typename T> class property<const T> : public base_property<T> {
public:
const T& get()const { return value; }
};
class ConstChild : public property<const int>{ };
I had the same need and I ended up with this quite manual approach :
class A
{
public:
void fooMutable(void) {}
void fooConst(void) const {}
};
class B : private A
{
public:
using A::fooConst;
const A& getParent(void) const
{
return *this;
}
};
void fooParent(const A&) {}
int main(void)
{
auto b = B{};
b.fooConst(); // Ok
b.fooMutable(); // Fail
fooParent(b); // Fail
fooParent(b.getParent()); // Ok
return 0;
}
Note that the using keyword would not work with overloads const/mutable :
class A
{
public:
void foo(void) {}
void foo(void) const {}
};
class B : private A
{
public:
using A::foo; // Expose the const and the mutable version
};
To solve this you could redefine the function yourself and call the parent :
class B : private A
{
public:
void foo(void) const
{
A::foo();
}
};
It can become pretty time consuming if you're inheriting a large hierarchy, but if it's for a not-so-big class it should be very reasonable and being quite natural for the user.
I have a trick, not a clean solution.
class ConstChild : private Property
{
operator const Property () { return *this; }
};
then
ConstChild cc;
cc.set(10); // ERROR
cc().get();

C++ : function pointer and class members

I have a problem with the following piece of code that can't even compile.
The problem is on the line
class2_ = new Class2(myFunction);
In fact, I don't now how to reference myFunction, I have also tried class2_ = new Class2(&Class3::myFunction); but the compiler still complains :(
2 constraints:
The function myFunction can't be declared as static
This code will be used in a Arduino base project, I can't use boost::bind
Could you please help me ?
Thanks.
class Class2 {
typedef void(*MyFunction) (int what);
MyFunction fn_;
public:
Class2(MyFunction fn) : fn_(fn) {}
void invoke(int val) {
fn_(val);
}
};
class Class3 {
Class2* class2_;
public:
Class3() {
class2_ = new Class2(myFunction);
class2_->invoke(12);
}
void myFunction(int what) {
// Do some work
}
};
void test2() {
Class3 instance3;
}
How about using an interface for that:
class ClassWithFunction {
public:
virtual void myFunction(int what) = 0;
}
class Class2 {
ClassWithFunction* fn_;
public:
Class2(MyFunction* fn) : fn_(fn) {}
void invoke(int val) {
fn_->myFunction(val);
}
};
class Class3 : ClassWithFunction {
Class2* class2_;
public:
Class3() {
class2_ = new Class2(this);
class2_->invoke(12);
}
void myFunction(int what) {
// Do some work
}
};
You need to use pointer to member function.
class Class3;
class Class2 {
typedef void(Class3::*MyFunction) (int);
MyFunction fn_;
public:
Class2(MyFunction fn) : fn_(fn) {}
void invoke(Class3 *p, int val) {
(p->*fn_)(val);
}
};
class Class3 {
Class2* class2_;
public:
Class3() {
class2_ = new Class2(&Class3::myFunction);
class2_->invoke(this, 12);
}
void myFunction(int what) {
// Do some work
}
};
If you want that Class2 accepts any callable object with signature void(int), then class template, function wrapper, lambda expression etc. will help.

Inherit from const class

I would like to inherit from a class with the const specifier like this:
class Property
{
int get() const;
void set(int a);
};
class ConstChild : public const Property
{
// Can never call A::set() with this class, even if
// the instantiation of this class is not const
};
class NonConstChild : public Property
{
// Can call both A::set() and A::get() depending on
// the constness of instantiation of this class
};
My compiler obviously gives me an error for the const keyword in the second classes declaration. Ideally I'd like to avoid having to create a new class ReadOnlyProperty from which ConstChild would inherit.
Can I somehow use the const keyword for inheritance?
If not, do you have any other ideas on how to solve this problem?
Introduce mutability later in your inheritance tree and derive appropriately:
class Property
{
int get() const;
};
class MutableProperty : public Property {
{
void set(int a);
};
And then:
class ConstChild : public Property { ... };
class MutableChild : public MutableProperty { ... };
I had the need for a related problem, which is: to really control/highlight mutable and const access on some class.
I did it with this simple reusable template wrapper:
template <typename T>
class TAccessor : private T
{
public:
const T& Const() const { return *this; }
T& Mutable() { return *this; }
};
// Example of use:
template <typename T>
using MyVector = TAccessor<std::vector<T>>;
void main()
{
MyVector<int> vector;
vector.Mutable().push_back(10);
int x = vector.Const()[1];
...
}
If you create a const member function set, you will get what you need.
class Property
{
int get() const;
void set(int a);
};
class ConstChild : public Property
{
void set(int a) const {}
};
The only caveat is that a sly user can circumvent your intention by using:
ConstChild child;
child.set(10); // Not OK by the compiler
Property& base = child;
base.set(10); // OK by the compiler
I would like to inherit from a class with the const specifier"
However much you want to is irrelevant. You cannot. That is not valid C++.
Can I somehow use the const keyword for inheritance?"
No.
Use a data member or private base class instead of public base class.
Then you control the access to that member.
You can make the Property thing an abstract interface if you need polymorphic behavior.
You can use a template class and a specialization for a constant type:
template<typename T> class base_property {
protected:
T value;
};
template<typename T> class property : public base_property<T> {
public:
const T& get()const { return value; }
void set(const T& v){ value = v; }
};
template<typename T> class property<const T> : public base_property<T> {
public:
const T& get()const { return value; }
};
class ConstChild : public property<const int>{ };
I had the same need and I ended up with this quite manual approach :
class A
{
public:
void fooMutable(void) {}
void fooConst(void) const {}
};
class B : private A
{
public:
using A::fooConst;
const A& getParent(void) const
{
return *this;
}
};
void fooParent(const A&) {}
int main(void)
{
auto b = B{};
b.fooConst(); // Ok
b.fooMutable(); // Fail
fooParent(b); // Fail
fooParent(b.getParent()); // Ok
return 0;
}
Note that the using keyword would not work with overloads const/mutable :
class A
{
public:
void foo(void) {}
void foo(void) const {}
};
class B : private A
{
public:
using A::foo; // Expose the const and the mutable version
};
To solve this you could redefine the function yourself and call the parent :
class B : private A
{
public:
void foo(void) const
{
A::foo();
}
};
It can become pretty time consuming if you're inheriting a large hierarchy, but if it's for a not-so-big class it should be very reasonable and being quite natural for the user.
I have a trick, not a clean solution.
class ConstChild : private Property
{
operator const Property () { return *this; }
};
then
ConstChild cc;
cc.set(10); // ERROR
cc().get();

How to make a class property type in C ++ as is how it is done in C#

as the code below made for example purposes in C #, I would have had to do in C ++, if so how do you do?
public class MyClassTest{
public int testint1{get;set;}
public MyClassTest2 classTest2{get;set;}
}
public class MyClassTest2{
public int testint2{get;set;}
public MyClassTest classTest{get;set;}
}
Something like this.
class MyClassTest {
private: // optional: C++ classes are private by default
int testint1;
public:
int getTestInt1() const { return testint1; }
void setTestInt1(int t) { testint1 = t; }
};
Or you could make your member name distinct and skip the get/set keywords:
class MyClassTest {
private:
int testint1_;
public:
int testint1() const { return testint1_; }
void testint1(int t) { testint1_ = t; }
};
There is no equivalent to this in the current C++ standard, you just have to create getter/setter methods for any fields you want:
class MyClass {
public:
MyClass() {}
// note const specifier indicates method guarantees
// no changes to class instance and noexcept specifier
// tells compiler that this method is no-throw guaranteed
int get_x() const noexcept { return x; }
void set_x(int _x) { x = _x; }
private:
int x;
};
In Visual Studio (mine is 2013), it could be done in this way:
__declspec(property(get = Get, put = Set)) bool Switch;
bool Get() { return m_bSwitch; }
void Set(bool val) { m_bSwitch = val; }
bool m_bSwitch;
in a Class.

Pimpl idiom used with a class member variable

Whats the correct way of implementing this class?
//Header
#include <boost/shared_ptr.hh>
class MyClass
{
public:
static foo()
static foobar();
private:
class pimpl;
static boost::shared_ptr<pimpl> m_handle;
static bool initialized;
};
//source
namespace
{
bool init()
{
//...
// init() can't access m_handle, unless it is a friend of MyClass
// but that seems a bit "tacky", is there a better way?
}
}
class MyClass::pimpl
{
public:
~pimpl(){}
}
bool MyClass::initialized = init();
MyClass::foo()
{
//...
}
MyClass::foobar()
{
//...
}
MyClass is a singleton -- some call it a glorified global. An oft-abused pattern. Use private ctors and a public static accessor:
MyClass {
public:
static MyClass& Instance() {
static MyClass obj;
return obj;
}
// ...
private:
MyClass() : m_handle(pimpl()), initialized(true) {}
// ...
};