|
-
June 11th, 2008, 05:56 PM
#1
Use of operator keyword
Hi everyone,
Can anyone help me in understanding the use of operator keyword in the following code -
class Font {
public:
...
operator FontHandle() const { return f; }
...
private:
FontHandle f;
};
I know the behaviour of this operator member, whenever the obj of Font class is used in an expression, this operator member is invoked. But I(with my limited knowledge of c++) cannot understand this declaration.
Thanks.
-
June 11th, 2008, 06:24 PM
#2
Re: Use of operator keyword
"const" after function name means that class itself isn't modified as a result of this member function call. Syntax is unusual for this case, you'd need to just get used to it, there is nothing to understand.
-
June 11th, 2008, 06:38 PM
#3
Re: Use of operator keyword
 Originally Posted by See++
I know the behaviour of this operator member, whenever the obj of Font class is used in an expression, this operator member is invoked. But I(with my limited knowledge of c++) cannot understand this declaration.
What you "Know" is just plain wrong.....
The declaration means that and instance of Font class may be implicitly cast to a FontHandle by returning the "f" member of the object.
The const on the end means that this method may be called on instances that are declared as const. It does NOT necessarily mean that the state of the instance is not modified.
ALL Methods should be declared const in this fashon unless they cause a visible modification to the state.
TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
2008, 2009,2010
In theory, there is no difference between theory and practice; in practice there is.
* Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions 
* How NOT to post a question here
* Of course you read this carefully before you posted
* Need homework help? Read this first
-
June 11th, 2008, 07:03 PM
#4
Re: Use of operator keyword
 Originally Posted by TheCPUWizard
The const on the end means that this method may be called on instances that are declared as const. It does NOT necessarily mean that the state of the instance is not modified.
Well, technically yes, but that'd be crazy, especially at this level of experience.
-
June 11th, 2008, 07:11 PM
#5
Re: Use of operator keyword
 Originally Posted by RoboTact
Well, technically yes, but that'd be crazy, especially at this level of experience. 
And when a person makes mistakes because he was tought something that was wrong (without being told it was wrong - or atleast a gross oversimplification)?????
Or when the person fails a job interview, stays out of work and looses his/her house, because of the same?
When I was in third grade (age 7), I had a very wise teacher. The very first day of school he told us that nearly everything he was going to teach us was incomplete, and therefore NOT a "Correct" answer in reality. However by pointing this out, it served the students very well in later years.
As a more complex example, Ihad to count the number of people who learn Newtonian physics (often starting in elementary school), without being told that everything is merely an approximation, but one that will be accurate for their daily lives (assuming they are "normal" people). They get totally destryed as they progress into higher levels as they find their belief of "knowing" to simply be an illusion.
Declaring a method const means one and only one thing. You can call it on an instance which is declared as const without having to cast away the constness.
TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
2008, 2009,2010
In theory, there is no difference between theory and practice; in practice there is.
* Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions 
* How NOT to post a question here
* Of course you read this carefully before you posted
* Need homework help? Read this first
-
June 11th, 2008, 07:59 PM
#6
Re: Use of operator keyword
 Originally Posted by TheCPUWizard
Declaring a method const means one and only one thing. You can call it on an instance which is declared as const without having to cast away the constness.
If you are a complier, yes. OK, I agree that knowing about the uncertainty is useful, but education requires understanding at the level at which material is presented. The most important levels of semantics in a program are in mental models of programmers who read and understand the code, runtime semantics is substrate that needs to be got correctly and types (apart from documentation and navigation benefits) enable immediate-feedback static checking. "const" is not about runtime semantics, it is for static checking, and its role as documentation adds conventional connotations to circumstances in which it's applied. So, there is a very real sense in which it does mean "object remains constant". It's just not a formal sense.
-
June 11th, 2008, 08:22 PM
#7
Re: Use of operator keyword
Agreed that it is a compile time only impact.
But any assumption is still wrong...
Code:
class X
{
public:
void f() const {.........}
void g() {.........}
int value;
}
X x;
int original = x.Value;
x.f(); // Hey the method is const....
int current = x.Value;
if (original != current)
printf("Pay the CPUWizard $1,000,000");
By YOUR rational, I would never get paid. However I can fill in very simple code for the "......" and make sure that everyone who runs the program has to pay me (collecting might be a problem. )
What the developer can count on is: (same class declaration)
Code:
X *x1 = new X();
X const * const x2 = new X();
x1->f(); // Good item not const - method dont matter...
x1->g(); // Good item not const - method dont matter...
x2->f(); / / Good item is const - so is method...
x2->g(); // Compiler Error! - item is const but method is NOT.
ANY other conclusions are simply making assumption on what is in ".......".
TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
2008, 2009,2010
In theory, there is no difference between theory and practice; in practice there is.
* Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions 
* How NOT to post a question here
* Of course you read this carefully before you posted
* Need homework help? Read this first
-
June 11th, 2008, 08:40 PM
#8
Re: Use of operator keyword
 Originally Posted by TheCPUWizard
ANY other conclusions are simply making assumption on what is in ".......".
Yes, that's one of the goals of documentation: specifying the functionality informally, which doesn't always allow you to figure out all the details, but gives a feel of the picture. Just like when you give a name to a method -- you can rename ReadMyFile to FormatHardDrive, and it won't change complile-time semantics or runtime semantics, but it'll screw up the code from readability (documentation) point of view. You can't rely on it with near-certainty, but you DO rely on it somewhat, otherwise it'd be useless, no?
-
June 11th, 2008, 10:13 PM
#9
Re: Use of operator keyword
There are reasons to be aware of the fact that a const method can modify data within the object, without resorting to pathological examples where the method changes the object's visible state.
Consider a get method that modifies an internal cache for performance reasons. The developer of this class figures that as far as the public interface of the class is concerned, the method does not modify anything. Now, at some point you decide to share an object of that class between threads... to be safe, you synchronize access to the object with a read-write mutex. Reader threads access the object through a const reference.
The gotcha is that the class does not synchronize access to its internal cache, so the assumption that const adequately expresses read-only access leads to a race condition when several threads "read" concurrently.
- Alon
-
June 11th, 2008, 10:54 PM
#10
Re: Use of operator keyword
Can we step back for just a second here - I am missing something crucial. CPUWizard, what code could you put into function f() that would change "value" and not cause a compiler error?
s
-
June 12th, 2008, 03:29 AM
#11
Re: Use of operator keyword
Well thanks for the comments. I am totatly aware of the const keyword and it uses. I do understand concepts of physical constness and logical constness.
May be I am missing something basic but the code 'operator FontHandle()' sounds mysterious to me. Can anyone help on this.
-
June 12th, 2008, 03:46 AM
#12
Re: Use of operator keyword
When Scott Meyers advised us to "do as the ints do", he wasn't just talking about making sure that overridden operators don't take other by surprise in their actions - the advice extends to all implied contracts between author and user. Yes, the only strict meaning that you can place on a const function is that is can be called on a const object, but the implied contract is that a const function will not change the observable state of the object. That's why "mutable is your friend" - but, then, there is a corrollary implied contract: that any member variable marked mutable does not contribute to the object's observable state.
If, as an author, CPUWizard presented me (as a user) with code that did change the observable state of a const object, then I would be very quickly paying him a visit in his cubicle - not to congratulate him on his ability to "play the rules", but to acquaint him with the wrong end of a rubber chicken.
As for the question about operator foo() - it's a type-conversion operator. It doesn't follow the normal function syntax (there's no return type) because the return type is implied in the name.
Providing user defined conversions is generally considered to be A Bad Thing(TM), since they provide a means for the compiler to silently plant code that does things that you are unaware of and probably don't want. Also, excessive use of UDCs simply provide more opportunities for ambiguous function overload resolution, and the concomitant pain of specifying which one you really want.
Careful programmers will almost always mark any constructor that can be called with a single argument as "explicit", and will eschew conversion operators in favour of named functions that do the same job (cf. std::string::c_str()).
Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
-- Sutter and Alexandrescu, C++ Coding Standards
Programs must be written for people to read, and only incidentally for machines to execute.
-- Harold Abelson and Gerald Jay Sussman
The cheapest, fastest and most reliable components of a computer system are those that aren't there.
-- Gordon Bell
-
June 12th, 2008, 04:18 AM
#13
Re: Use of operator keyword
 Originally Posted by Graham
When Scott Meyers advised us to "do as the ints do", he wasn't just talking about making sure that overridden operators don't take other by surprise in their actions - the advice extends to all implied contracts between author and user. Yes, the only strict meaning that you can place on a const function is that is can be called on a const object, but the implied contract is that a const function will not change the observable state of the object. That's why "mutable is your friend" - but, then, there is a corrollary implied contract: that any member variable marked mutable does not contribute to the object's observable state.
If, as an author, CPUWizard presented me (as a user) with code that did change the observable state of a const object, then I would be very quickly paying him a visit in his cubicle - not to congratulate him on his ability to "play the rules", but to acquaint him with the wrong end of a rubber chicken.
As for the question about operator foo() - it's a type-conversion operator. It doesn't follow the normal function syntax (there's no return type) because the return type is implied in the name.
Providing user defined conversions is generally considered to be A Bad Thing(TM), since they provide a means for the compiler to silently plant code that does things that you are unaware of and probably don't want. Also, excessive use of UDCs simply provide more opportunities for ambiguous function overload resolution, and the concomitant pain of specifying which one you really want.
Careful programmers will almost always mark any constructor that can be called with a single argument as "explicit", and will eschew conversion operators in favour of named functions that do the same job (cf. std::string::c_str()).
That helps. many thanks.
-
June 12th, 2008, 05:13 AM
#14
Re: Use of operator keyword
If, as an author, CPUWizard presented me (as a user) with code that did change the observable state of a const object, then I would be very quickly paying him a visit in his cubicle - not to congratulate him on his ability to "play the rules", but to acquaint him with the wrong end of a rubber chicken.
Could somebody please explain me what it means in plain english.Particularly the connotation of rubber chicken part.
Dont forget to rate my post if you find it useful.
-
June 12th, 2008, 06:12 AM
#15
Re: Use of operator keyword
I read it as - if Graham used code written by TheCPUWizard and found that this code changed the observable status of an object when one of the object's const members was called then Graham would walk into the office/cubicle of TheCPUWizard and bring with him a rubber chicken and probably hit TheCPUWizard with it.
I presume that this is customary behaviour at Graham's place of employment.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|