Re: [Dev-C++] classes and references
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: <or...@vp...> - 2003-05-03 23:46:42
|
Goran Kavrecic wrote:
> try defining your return type as a reference with a simple and(&) after the class name.
>
> myclass& make_myclass(void)
> {
> myclass mc_tmp;
> return mc_tmp;
> }
Well, of course, but this sounds too simple. Besides I have already
tried it, and it gives a warning: "reference returned to local variable"
or something.
I am pondering, it has something to do with const stuff.
(... 5 mins trial ...)
BINGO!!!
I have changed the use_myclass function to this:
static void use_myclass(const myclass& mc){
printf("Value: %d\n",mc.value);
}
and it worked!
(... 5 mins reading ...)
YIPEE!!! I have also found the explanation in the book!!! :)))
So: when I call
use_myclass(make_myclass());
then make_myclass() will return with a local variable, thus causing the
copy constructor to get called. It will make a copy and place into a
TEMPORARY variable, then pass THAT for use_myclass()
The book sais (rough translation):
"We may use a temporary variable to initialize a constant."
BUT "... a temporary variable *cannot* be used to initialize a
non-constant reference"
So this is why I didn't work. It tried to initialise the parameter of
use_myclass(myclass&) (a reference) with a TEMPORARY variable. This is
illegal.
MSVC and BORLAND *_SUCKS_*!!! They support hacks!!! >:(
My, thank you pal. You drived my attention to the right part! Thanks,
really! :)
Oh, BTW one should *never* return a reference to a local variable. That
is written in the book, and it is also understandable. Because it will
be deleted, before it could be used.
Well, I got cleverer. I think I will be able to handle C++ well. So,
questions are welcome, least I will look it up, so I will learn too.
And again, thanks for you swift response.
--
Greetings,
Balázs
|