An attempt to make a 'property' in C++

P

Pavel Shved

Hello.

Some languages contain so-called 'properties' - class members that
behave in different ways depending on whether you read or modify them.
I wonder whether is can be declared like this:

class A{
...

int& Prop()
{
//When we write to some kind of field
m_modified = true; //Lets assume for example, that we need to
know
//whether we use property for writing.
return m_field;
};
const int& Prop() const
{
//When we read something from field
return m_field;
};

};


Will the non-constant function be invoked only when the value returned
is being modified?
 
V

Victor Bazarov

Pavel said:
Some languages contain so-called 'properties' - class members that
behave in different ways depending on whether you read or modify them.
I wonder whether is can be declared like this:

class A{
...

int& Prop()
{
//When we write to some kind of field
m_modified = true; //Lets assume for example, that we need to
know
//whether we use property for writing.
return m_field;
};
const int& Prop() const
{
//When we read something from field
return m_field;
};

};


Will the non-constant function be invoked only when the value returned
is being modified?

No. Non-constant function will be invoked for any non-constant 'A' object.
Why reinvent the wheel? Look on the Web for examples of decent property
implementations.

V
 
?

=?iso-8859-1?q?Elias_Salom=E3o_Helou_Neto?=

You get the answer here:

http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.12

It mainly states that the const member function will be called only
when the class instance calling it is itself const. The following
program shows it:

#include <iostream>

class ConstTest
{
public:

ConstTest( void ){}

const bool& get( void ) const
{
std::cout << "Const.\n";
return( _b );
}
bool& get( void )
{
std::cout << "Not const.\n";
return( _b );
}

private:

bool _b;
};

int main( int argc, char* argv[], char* env[] )
{
ConstTest obj1;
const ConstTest obj2;

obj1.get();
obj1.get() = false;

obj2.get();
}

Compile and run the above program to get:

Not const.
Not const.
Const.

I guess that you'd better stick to the set/get names. Just rename the
non-const get() to set() and you are done. If you are going to write
two separate functions to each property anyway, why not to do it?

If lots of attribute of your class are to be set/get as a property you
may end up writing much less code by providing a template class to the
properties.

That's all, I guess.

Elias Salomão Helou Neto.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,776
Messages
2,569,602
Members
45,185
Latest member
GluceaReviews

Latest Threads

Top