Hi Group,
sorry for my for you surely dumb question. But i'm not so familiar with this
reference- and pointerstew in C++ yet.
Let me explain my problem with a little Codesnippet.
If i do the following:
void CServerSock::On Accept(void)
{
CSocket clientsock;
.... // some irrelevant code here
this->Accept(clients ock);
.... // some irrelevant code here
}
all went fine. The function Accept is a Member of CServerSock and documented
as
void Accept(CSocket &)
I understand it this way, that the Accept-Function takes a Reference to a
CSocket-Object, right? But there is a problem for me. The Documentation for
CSocket says further:
"If the Object goes out of scope, the connection is automatically
closed"
So, as the Object in my a.m. example is created on the stack, it goes out of
scope immediately when the OnAccept()-Function ends. And than the connection
is closed (what i don't want to happen now!)
The documentation for Accept says:
"The referenced Object can be created on the stack or on the heap"
Yeah! That's it! I thought! I have to create my socket-object on the heap
instead. So i tried sth. like that:
void CServerSock::On Accept(void)
{
CSocket *clientsock = new CSocket();
.... // some irrelevant code here
this->Accept(clients ock);
.... // some irrelevant code here
}
But now the compiler complains with:
"Cannot convert from class CSocket * to class CAsyncSocket &"
(CSocket is derived from CAsyncSocket - so it should work, isn't it?)
So the problem must be, that a csocket* (Pointer) is sth. different from
csocket& (Reference). I read many pages on the net which states that a
Reference is a const pointer to sth. a.s.o. but i never discovered the
general idea and the background.
Tried a lot versions with
- CSocket const *clientsock
- const CSocket *clientsock
- and, and, and, ...
Nothing worked. Sometimes other errors in the compiler occured, often the
same again and again. Sometimes no error occured and i was able to compile.
But then, at runtime, i get a programcrash for the not right reference to
the object.
So my question is:
How can i get (How must i note to get) a Reference to a memory block/Object
that was created on the heap with the new operator. How can i get a & to an
object when i only have a * to it? How can i keep the compiler happy?
I take the syntax alone, but i really will be happy if there are 1 or 2
sentences of explanation why it should be so or so and not the other way. Is
there a simple explanation how i have to imagine a Reference or a Pointer
(the difference) so i am able to understand it and solve my future problems
with such things on my own (i like more to learn than only to solve sth.).
Any good (understandable for such a lamer like me) webpages out there?
Thx. in advance! Your help, hints, urls, explanations, solutions, money
:-))), best wishes :-))) are really appreciated!
CU
Joerg Toellner