C++Talk.NET Forum Index C++Talk.NET
C++ language newsgroups
 
Archives   FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

Restricting member functions from chaging a member variable.

 
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ Language (Moderated)
View previous topic :: View next topic  
Author Message
tojohere@gmail.com
Guest





PostPosted: Mon Jun 27, 2005 10:40 am    Post subject: Restricting member functions from chaging a member variable. Reply with quote



Hello,
I want to make a member variable of my class as it can be modified only
in a specific member function(s).
Is that possible in any way....?
I tried many ways but finally I arrived in a dirty idea...( Also not
that perfect )... but it works...
The code is shown below....
-----------------------------------------------------------------------------------------------------------
class Boy
{
private:
const int m_nCount;
public:
Boy()
:m_nCount ( 0 )
{
}
void SetCount( int argCount)
{
*( const_cast <int *> ( &m_nCount ) ) = argCount;
// This can be possible from anywhere
// in the class if the programmer is
// that much crooked to do like this...Smile
}
int GetCount()
{
return m_nCount;
}
void SomeFunc()
{

m_nCount++; // Error : compiler will prevent this just
becoz its a const.

SetCount( GetCount() + 1); // This will work without any
problem.
// I want the programmer to
force
// to do like this when he
modify the m_nCount
}
};

int main(int argc, char* argv[])
{
Boy b;
b.SetCount( 10 );
int a = b.GetCount();
return 0;
}
-----------------------------------------------------------------------------------------------------------
I feels this as dirty idea because I heard that casting away cost is
not a good practice.
Does any body know any other better idea to do this?
Thanks in advance for you valued advice.


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Back to top
Mark Van Peteghem
Guest





PostPosted: Mon Jun 27, 2005 12:55 pm    Post subject: Re: Restricting member functions from chaging a member varia Reply with quote



You could define a new class Count that has the member variable
m_nCount, that is private, and the methods SetCount and GetCount.
Then derive Boy from that class:

class Count
{
private:
int m_nCount;
public:
Count(int c): m_nCount(c) {}

void SetCount( int argCount)
{
m_nCount = argCount;
}
int GetCount()
{
return m_nCount;
}
};

class Boy: public Count
{
public:
Boy(): Count ( 0 )
{
}

void SomeFunc()
{
// Error : compiler will prevent this
// because it's private in superclass.
m_nCount++;

// This will work without any problem.
// I want the programmer to force
// to do like this when he modify the m_nCount
SetCount( GetCount() + 1);
}
};

--
Mark dot Van dot Peteghem at q-mentum dot com
http://www.q-mentum.com -- easier and more powerful unit testing

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Back to top
pinto
Guest





PostPosted: Mon Jun 27, 2005 1:00 pm    Post subject: Re: Restricting member functions from chaging a member varia Reply with quote



why do not u try to use a parent class and put the m_nCount in the
parent

class human
{
protected:
void setcount(int _iCount){i_Count=_iCount;};
int GetCount(){return i_Count;};
private:
int i_Count;
};

class Boy: public human
{
};


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Back to top
Hendrik Belitz
Guest





PostPosted: Mon Jun 27, 2005 1:01 pm    Post subject: Re: Restricting member functions from chaging a member varia Reply with quote

[email]tojohere (AT) gmail (DOT) com[/email] wrote some weird stuff.

Why do you want to do such a thing at all? Is there a good reason for not
allowing all member functions access to the member variable?



--
- Abort, Retry, Fthagn? -

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Back to top
Michael Tiomkin
Guest





PostPosted: Tue Jun 28, 2005 9:51 am    Post subject: Re: Restricting member functions from chaging a member varia Reply with quote

[email]tojohere (AT) gmail (DOT) com[/email] wrote:
Quote:
Hello,
I want to make a member variable of my class as it can be modified only
in a specific member function(s).
Is that possible in any way....?
I tried many ways but finally I arrived in a dirty idea...( Also not
that perfect )... but it works...
The code is shown below....


You can hide this var in a class, and use friend member functions to
hide its change from other member functions. Let's assume that the type
of this "var" is U.

class C;

class hide_U_in_C
{
U val;
public:
hide_U_in_C(U v): val(v) {}
const U& get() { return val;}

friend char C::get_char(int param);
// other friend methods of C ...
};

class C
{
hide_U_in_C v;
.....
};

char C::get_char(int i)
{
// can directly change v.val
}


BTW, many people will say that using friends isn't very nice and that
it's a result of bad design.
A simpler solution might be to define the base class with all the
methods that should be able to change the value, and put all the
"other" methods in the derived class:

class C_0
{
U val;
...
public:
.... all the methods that change val ...

};

class C: public C_0
{
// C methods cannot directly change val
}

Michael


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


Back to top
Tojo
Guest





PostPosted: Tue Jun 28, 2005 9:56 am    Post subject: Re: Restricting member functions from chaging a member varia Reply with quote

Hendrik Belitz wrote:
Quote:
tojohere (AT) gmail (DOT) com wrote some weird stuff.

Why do you want to do such a thing at all?
Ans:- Consider a situation we have to do some vlidation in the setter

function of a member variable, if the setter is there and still the
programmer( who may be somebody else who wrote the setter) may modify
the variable directly from inside other class member functions.

Is there a good reason for not
Quote:
allowing all member functions access to the member variable?
Ans:- I just wanted to prevent such direct modification of a variable,

from inside the class, using some language level protection.
The variable should be modified only through the setter method.
Thats all.


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


Back to top
Tojo
Guest





PostPosted: Tue Jun 28, 2005 9:58 am    Post subject: Re: Restricting member functions from chaging a member varia Reply with quote

Yeah I thought about this idea first,
But just for a variable, creating one base class felt as an
overhead to me. Also I thought about maintaining an internal structure
or class like this

class Boy
{
private:
struct Count
{
private:
int m_nCount;
public:
Count() :m_nCount(0) { }

void SetCount(int argCount)
{
m_nCount = argCount;
}
int GetCount()
{
return m_nCount;
}

} st_Count;

public:
Boy(): st_Count ( )
{
}
void SetCount(int argCount)
{
st_Count.SetCount( argCount );
}
int GetCount()
{
return st_Count.GetCount();
}

void SomeFunc()
{
// Error : compiler will prevent this
// because there is no ++ operator overloaded for Count
structure.
st_Count++;

// This will work without any problem.
// I want the programmer to force
// to do like this when he modify the m_nCount
SetCount( GetCount() + 1);
}
};


int main(int argc, char* argv[])
{
Boy b;
b.SetCount( 10 );
int a = b.GetCount();
return 0;
}

But you can see how much extra code I have to write to achieve such a
simple thing. Thats why I finally decided to use 'const' approach.
The 'cost' approch doesn't need to introduce any new classes or
structure....thats the benefit I am seeing in that style. But that too
feels as wrong even if it works....


Mark Van Peteghem wrote:
Quote:
You could define a new class Count that has the member variable
m_nCount, that is private, and the methods SetCount and GetCount.
Then derive Boy from that class:

class Count
{
private:
int m_nCount;
public:
Count(int c): m_nCount(c) {}

void SetCount( int argCount)
{
m_nCount = argCount;
}
int GetCount()
{
return m_nCount;
}
};

class Boy: public Count
{
public:
Boy(): Count ( 0 )
{
}

void SomeFunc()
{
// Error : compiler will prevent this
// because it's private in superclass.
m_nCount++;

// This will work without any problem.
// I want the programmer to force
// to do like this when he modify the m_nCount
SetCount( GetCount() + 1);
}
};


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


Back to top
tony_in_da_uk@yahoo.co.uk
Guest





PostPosted: Tue Jun 28, 2005 10:17 am    Post subject: Re: Restricting member functions from chaging a member varia Reply with quote

You're getting caught up in the doomed pursuit of over-protecting your
class. Just as private can be circumvented by body practices such as
"#define private public", const can be circumvented by things like
"reinterpret_cast<int&>(b) = 3". There's no point fighting this - if a
client programmer is dumb enough to do this, they deserve whatever
happens to them.

What you've already done isn't too bad, though it's a choice between
evils: having a const int as you've done mistakenly implies the class
doesn't need to change it after construction, which could confuse a
programmer maintaining your code, while omitting const doesn't convey
that changing the value requires special caution. Either way, a
comment should appear beside the declaration explaining that it must
only be changed in SetCount(). As a guideline, you shouldn't make it
const unless you anticipate attempts to try to change it
inappropriately. Will other programmers write or maintain the
functions in this class? Will the class be so large they can't easily
take in the complexity and ramifications of changing the count? If so,
then perhaps you should refactor your code. If you're really serious
about preventing changes to the value, then you could use an operating
system call to lock the memory (on UNIX, mprotect), but then attempts
to access it will generate signals that, if unhandled, may make your
app fall over, and are problematic to recover from.

Cheers, Tony


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Back to top
kanze@gabi-soft.fr
Guest





PostPosted: Wed Jun 29, 2005 11:19 am    Post subject: Re: Restricting member functions from chaging a member varia Reply with quote

[email]tojohere (AT) gmail (DOT) com[/email] wrote:

Quote:
I want to make a member variable of my class as it can be
modified only in a specific member function(s). Is that
possible in any way....?

No.

Quote:
I tried many ways but finally I arrived in a dirty idea...(
Also not that perfect )... but it works...

The code is shown below....

-------------------------------------------------------------------
class Boy
{
private:
const int m_nCount;
public:
Boy()
:m_nCount ( 0 )
{
}
void SetCount( int argCount)
{
*( const_cast <int *> ( &m_nCount ) ) = argCount;
// This can be possible from anywhere
// in the class if the programmer is
// that much crooked to do like this...Smile
}
int GetCount()
{
return m_nCount;
}
void SomeFunc()
{

m_nCount++; // Error : compiler will prevent this just
becoz its a const.

But the compiler won't prevent using the same trick as you used
in SetCount. Anything you can do in the setter, you can do in
any other function.

Quote:
SetCount( GetCount() + 1); // This will work without any
problem.
// I want the programmer to
force
// to do like this when he
modify the m_nCount
}
};

int main(int argc, char* argv[])
{
Boy b;
b.SetCount( 10 );
int a = b.GetCount();
return 0;
}
-------------------------------------------------------------------
I feels this as dirty idea because I heard that casting away cost is
not a good practice.
Does any body know any other better idea to do this?

The only real solution is to use a separate class:

class Boy
{
private:
class Counter
{
public:
Counter( int init ) : myValue( init ) {}
void set( int newValue ) { myValue = init ; }
int get() { return myValue ; }
private:
Counter( Counter const& ) ;
Counter& operator=( Counter const& ) ;
int myValue ;
} m_count ;

// ...
} ;

Any code that you would have put in getCount() and setCount()
goes in the get and set functions of Counter.

--
James Kanze GABI Software
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


Back to top
Mark Van Peteghem
Guest





PostPosted: Wed Jun 29, 2005 1:57 pm    Post subject: Re: Restricting member functions from chaging a member varia Reply with quote

Tojo wrote:

Quote:
[...]
But you can see how much extra code I have to write to achieve such a
simple thing. Thats why I finally decided to use 'const' approach.
The 'cost' approch doesn't need to introduce any new classes or
structure....thats the benefit I am seeing in that style. But that too
feels as wrong even if it works....


Of course that means that every non-const method can still change it.

If you have only one non-const method, or every non-const is allowed
to change it, that is the ideal solution. Otherwise you need a
separate class to inherit from (as in my example) or encapsulate (as
in your example).

--
Mark dot Van dot Peteghem at q-mentum dot com
http://www.q-mentum.com -- easier and more powerful unit testing

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


Back to top
Display posts from previous:   
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ Language (Moderated) All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2006 phpBB Group
SEO toolkit © 2004-2006 webmedic.