473,657 Members | 2,896 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to do it: Pointer to Reference?

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
Jul 19 '05 #1
3 20518
On Mon, 14 Jul 2003 10:19:13 +0200, "JoTo" <to******@oss-gmbh.de> wrote:
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 &"


You have a pointer, the argument must be an object, to get an object
(the thing pointed to) from a pointer do
Accept( *clientsock );
But you have a more severe problem, that the CSocket object is never
deallocated.

One possibility could be to make this object a member of CServerSock.
Jul 19 '05 #2
Hello Alf and Group,

"Alf P. Steinbach" <al***@start.no > schrieb im Newsbeitrag
news:3f******** *******@News.CI S.DFN.DE...
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 &" You have a pointer, the argument must be an object, to get an object
(the thing pointed to) from a pointer do
Accept( *clientsock );


Hmmm! I thought i tried this variant already with the same result (compile
error). But maybe i only think i have done THIS variant in the mess i've
done with "fishing in the dark" :-) . So i try it again and will see.
But you have a more severe problem, that the CSocket object is never
deallocated.
One possibility could be to make this object a member of CServerSock.


Thx for the hint. I have already a member variable

CSocket *myclient[3];

in my Application-Object where i store the pointer in the OnAccept function
(in the irrelevant code sections) with

myapp->myclient[x] = clientsock;

(where x is 0|1|2 in case which clientsock is "free" at the moment)
And of course i'll do a

delete(myapp->myclient[x]);

later (on end of connection, end of app, a.s.o.). Is this enough for what
you suggest?

I need more than one clientsocks (there should be 3 connections at the same
time possible) and use the clientsock later for sending msgs to the
connected participants (thats why i must create it on the heap).

I hope this is what you meant with your "deallocate "-hint. If not please
explain further if possible what i need to do.

But let me first thank you very much for your fast reply. I'll try it and
cross my fingers with hope. :-)) Sometimes C++ is like black magic and vodoo
for me. But I'll get it ......... sometimes! :-)))

CU and Thx.
Joerg Toellner
Jul 19 '05 #3
Thanks Andrew,

i'll try it when i'm at home this evening. I hope the compiler has the same
opinion like you and all the others here. :-))))

Thx. all for you patience.
Where is the desk where i have to pay the bill now? :-))

Yours
Joerg Toellner

"Andrew Koenig" <ar*@acm.org> schrieb im Newsbeitrag
news:yu******** ******@tinker.r esearch.att.com ...
Let me summarize the problem.
You write
CSocket clientsock;
this -> Accept(clientso ck);
and it works just fine except for the fact that clientsock is a
local variable and is therefore destroyed at the wrong time.
So you want to create the object on the heap instead.
Here's how to do that:
CSocket* socket_ptr = new CSocket;
this -> Accept(*socket_ ptr);
And then, when you're done with the object, delete it:
delete socket_ptr;

Jul 19 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

110
9899
by: Mr A | last post by:
Hi! I've been thinking about passing parameteras using references instead of pointers in order to emphasize that the parameter must be an object. Exemple: void func(Objec& object); //object must be an object instead of
9
2994
by: Sandy | last post by:
Hi, In one of my interview I was asked a question, whether using pointers for argument is efficient then reference or not. i.e. void fun(Complex *p) void fun(Complex &ref) can somebody tell me which one will be more efficient and why? as far as i know both must be same, because i read somewhere that internally
18
3523
by: man | last post by:
can any one please tell me what is the diff between pointer and reference.....and which one is better to use ....and why???????
12
5384
by: Mike | last post by:
Consider the following code: """ struct person { char *name; int age; }; typedef struct person* StructType;
13
2652
by: al.cpwn | last post by:
I get that these two are different int* get() { static int m; return &m; } int& get() {
51
4434
by: Kuku | last post by:
What is the difference between a reference and a pointer?
8
2396
by: toton | last post by:
HI, One more small doubt from today's mail. I have certain function which returns a pointer (sometimes a const pointer from a const member function). And certain member function needs reference (or better a const reference). for eg, const PointRange* points = cc.points(ptAligned);
33
5048
by: Ney André de Mello Zunino | last post by:
Hello. I have written a simple reference-counting smart pointer class template called RefCountPtr<T>. It works in conjunction with another class, ReferenceCountable, which is responsible for the actual counting. Here is the latter's definition: // --- Begin ReferenceCountable.h ---------- class ReferenceCountable
2
35560
weaknessforcats
by: weaknessforcats | last post by:
Handle Classes Handle classes, also called Envelope or Cheshire Cat classes, are part of the Bridge design pattern. The objective of the Bridge pattern is to separate the abstraction from the implementation so the two can vary independently. Handle classes usually contain a pointer to the object implementation. The Handle object is used rather than the implemented object. This leaves the implemented object free to change without affecting...
41
3639
by: Summercool | last post by:
Can we confirm the following? also someone said, Java also has "reference" like in C++, which is an "implicit pointer": Pointer and Reference --------------------- I am starting to see what pointer and reference are and how they relate to each other.
0
8820
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8718
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8499
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8601
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7314
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5630
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4300
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1937
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1601
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.