473,786 Members | 2,447 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

When to use pointers in a class?

Is there some rule of thumb about when to use pointers to an object and
when to use a reference* to an object when a class needs to have objects
as data members?

Example:
class A
{
B* b_ptr;
B b;
vector<B*> vector_ptrs;
vector<B> vector_objects;
};

How do I know when to use pointers and when not to use them?

Thanks,
Joe

* I'm not sure if my terminology is correct here, please correct me if
I'm wrong. I'm also slightly confused about the relationship between
references and pointers. I know a reference is an alias of an object
and a pointer contains some address that's usually the start of the
object's location in memory, but I'm still not sure what the real
difference is.
Mar 21 '06 #1
20 2129
Joe Van Dyk wrote:
Is there some rule of thumb about when to use pointers to an object and
when to use a reference to an object when a class needs to have objects
as data members?
Prefer a reference unless you need a pointer's extra features.
Example:
class A
{
B* b_ptr;
Prefer a reference (seated in A::A), unless you need b_ptr==NULL for special
situations.

Then, as your designing gets more advanced, create a NullB, derived from B,
for use when there's no B, and seat or point b_ptr to it. NULL pointers
should be replaced with Null Objects that do nothing. This simplifies the
calling code.
B b;
vector<B*> vector_ptrs;
A pointer can be copied as an object, so you can't use a reference there. (I
doubt the template will even expand on one.
vector<B> vector_objects;
That is a copy, not a reference. Prefer one, if B is cleanly copiable, in
preference to pointers _or_ references.

The simpler the better.
* I'm not sure if my terminology is correct here, please correct me if
I'm wrong. I'm also slightly confused about the relationship between
references and pointers. I know a reference is an alias of an object
and a pointer contains some address that's usually the start of the
object's location in memory, but I'm still not sure what the real
difference is.


Sometimes a reference is a pointer with the indirection * already turned on.
That's how to start thinking about them, but the alias definition is more
powerful because the language permits subtle optimizations, such as
temporaries, via that definition.

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
Mar 21 '06 #2

"Phlip" <ph*******@gmai l.com> wrote in message
news:35******** *****@newssvr24 .news.prodigy.n et...
Joe Van Dyk wrote:
Is there some rule of thumb about when to use pointers to an object and
when to use a reference to an object when a class needs to have objects
as data members?
Prefer a reference unless you need a pointer's extra features.


As a data member? Why? I rarely use references as members.

I'd say prefer to use a member object (such as the member 'b' in the
example) over pointer members (such as member 'b_ptr' in the example).

Perhaps you're thinking of function parameters? For those, I'd agree that a
reference (or const reference) may be preferable to a pointer, unless there
is some need for a pointer, such as allowing a NULL value.
Example:
class A
{
B* b_ptr;
Prefer a reference (seated in A::A), unless you need b_ptr==NULL for
special
situations.


I don't understand. You mean you'd prefer

class A
{
B& b;
//...
};

over

class A
{
B b;
//...
};

....?

Sounds like you're assuming that an instance of B resides outside the A
class, prior to the construction of an instance of A, which is available to
pass to A's constructor. But the OP made no such inference.

Then, as your designing gets more advanced, create a NullB, derived from
B,
for use when there's no B, and seat or point b_ptr to it. NULL pointers
should be replaced with Null Objects that do nothing. This simplifies the
calling code.
B b;
vector<B*> vector_ptrs;


A pointer can be copied as an object, so you can't use a reference there.
(I
doubt the template will even expand on one.
vector<B> vector_objects;


That is a copy, not a reference. Prefer one, if B is cleanly copiable, in
preference to pointers _or_ references.


Well, there are at least two reasons why I might (and usually do, in
practice) prefer pointers in vectors over objects. One is that I might want
to make use of polymorphism, and I can only do that with a pointer or
reference. The other is that the copying of objects _may_ be expensive or
otherwise undesired.

Smart pointers as vector members, I am told, are an even better solution in
many cases.

-Howard
Mar 21 '06 #3
Howard wrote:
Prefer a reference unless you need a pointer's extra features.
As a data member? Why? I rarely use references as members.


I rarely write new C++ code. My job is troubleshooting existing C++. Code
that learned the C style, such as pointer abuse, drives me nuts. It doesn't
necessarily slow me down, though.

Maybe your members frequently repoint to other objects? Then you need
pointers.
Perhaps you're thinking of function parameters? For those, I'd agree that
a reference (or const reference) may be preferable to a pointer, unless
there is some need for a pointer, such as allowing a NULL value.
Same rule; use a pointer only if you need its extra features.

Now read MFC code, or C++ code driving RenderWare. Everyone passes pointers
everywhere, even where passing a NULL makes no sense, even where a
NullObject would work perfectly. Bleah!
I don't understand. You mean you'd prefer

class A
{
B& b;
//...
};

over

class A
{
B b;
//...
};

...?
If A can own the B, use the last one. It's the _weakest_ construction, with
the _least_ extra features.
Sounds like you're assuming that an instance of B resides outside the A
class, prior to the construction of an instance of A, which is available
to
pass to A's constructor. But the OP made no such inference.
I did. I ass-u-me-d that the OP knew to prefer member objects over handles
of any kind.
Well, there are at least two reasons why I might (and usually do, in
practice) prefer pointers in vectors over objects. One is that I might
want to make use of polymorphism, and I can only do that with a pointer or
reference. The other is that the copying of objects _may_ be expensive or
otherwise undesired.
When you need the extra features pointers provide, use them.
Smart pointers as vector members, I am told, are an even better solution
in many cases.


If they are indeed smart enough ;-)

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
Mar 21 '06 #4
Joe Van Dyk wrote :
Is there some rule of thumb about when to use pointers to an object and
when to use a reference* to an object when a class needs to have objects
as data members?


If you don't need pointers, dont use pointers.
Mar 21 '06 #5
Phlip wrote:
Joe Van Dyk wrote:

Is there some rule of thumb about when to use pointers to an object and
when to use a reference to an object when a class needs to have objects
as data members?

Prefer a reference unless you need a pointer's extra features.


In which situations would I want a pointer's extra features, and what
are those extra features?
Example:
class A
{
B* b_ptr;

Prefer a reference (seated in A::A), unless you need b_ptr==NULL for special
situations.


By "seated in A::A", you mean put into A's constructor?

Then, as your designing gets more advanced, create a NullB, derived from B,
for use when there's no B, and seat or point b_ptr to it. NULL pointers
should be replaced with Null Objects that do nothing. This simplifies the
calling code.

B b;
vector<B*> vector_ptrs;

A pointer can be copied as an object, so you can't use a reference there. (I
doubt the template will even expand on one.

vector<B> vector_objects;

That is a copy, not a reference. Prefer one, if B is cleanly copiable, in
preference to pointers _or_ references.


Would a reference to vector objects look like:
vector<B&> vector_objects
?

If I had the following function:
void add_stuff_to_th e_vector()
{
B b;
b.foo = "Hello"
vector_objects. push_back(b);
}

Would that be ok? The push_back'd object that there's a reference to in
the vector wouldn't disappear after the function ends?

The simpler the better.

* I'm not sure if my terminology is correct here, please correct me if
I'm wrong. I'm also slightly confused about the relationship between
references and pointers. I know a reference is an alias of an object
and a pointer contains some address that's usually the start of the
object's location in memory, but I'm still not sure what the real
difference is.

Sometimes a reference is a pointer with the indirection * already turned on.
That's how to start thinking about them, but the alias definition is more
powerful because the language permits subtle optimizations, such as
temporaries, via that definition.


Hmm.. ok. I'll ponder that one.

Thanks, you've been quite helpful!

Joe
Mar 21 '06 #6

"Joe Van Dyk" <jo********@boe ing.com> wrote in message
news:Iw******** @news.boeing.co m...
Is there some rule of thumb about when to use pointers to an object and
when to use a reference* to an object when a class needs to have objects
as data members?

Example:
class A
{
B* b_ptr;
B b;
vector<B*> vector_ptrs;
vector<B> vector_objects;
};

How do I know when to use pointers and when not to use them?

Thanks,
Joe

* I'm not sure if my terminology is correct here, please correct me if I'm
wrong.
Your question asks about something you called "reference* ". There's no such
thing as a "reference* ". Did you just mean "reference" ?

Also, your example shows a B* pointer member and a B object member , and
doesn't show any reference members at all.

So I guess I'm confused as to what your question really means.

I'm also slightly confused about the relationship between references and
pointers. I know a reference is an alias of an object and a pointer
contains some address that's usually the start of the object's location in
memory, but I'm still not sure what the real difference is.


A good book will help you the most here.

-Howard

Mar 21 '06 #7
On 21/03/2006, Joe Van Dyk wrote:
Is there some rule of thumb about when to use pointers to an object
and when to use a reference* to an object when a class needs to have
objects as data members?

Example:
class A
{
B* b_ptr;
B b;
vector<B*> vector_ptrs;
vector<B> vector_objects;
};

How do I know when to use pointers and when not to use them?


Let's look at another example:

class A
{
B* b_ptr; // pointer to B
B& b_ref; // reference to B
};

Using the reference is more restrictive. You must assign the reference
in A's constructor. So the instance of B which b_ref is referring to
must exist before A is created. You can't decide part way through the
life of A to change b_ref to refer to a different instance of B (ie you
can't reseat a reference.) If your design allows you to live with these
restrictions, the use of a reference will help you to write more
error-free code and will help other programmers who read your code.

Using the pointer, you can do these things which you can't do with a
reference:

* You can assign b_ptr at a point later than when A is constructed.
This can be useful in class factories, avoiding brittle constructors
etc. It can also be useful where an instance of B can't be created
before the instance of A.

* A can assume ownership of b_ptr, creating it with 'new' in A's
constructor, deleting it in A's destructor.

* b_ptr can be reassigned to point to a different B part way through
the lifetime of A.

* b_ptr can be null, can point to a deleted object, can be
uninitialised so it points to a random memory location. These all
result in the sort of errors which can be hard to track down. (OK, you
can do some of the above with a reference, but you have to work harder
at it!)

--
Simon Elliott http://www.ctsn.co.uk
Mar 22 '06 #8

"Joe Van Dyk" <jo********@boe ing.com> wrote in message
news:Iw******** @news.boeing.co m...
Phlip wrote:
Joe Van Dyk wrote:

Is there some rule of thumb about when to use pointers to an object and
when to use a reference to an object when a class needs to have objects
as data members?

Prefer a reference unless you need a pointer's extra features.


In which situations would I want a pointer's extra features, and what are
those extra features?


I mentioned two reasons in my post earlier in this sub-thread.
Would a reference to vector objects look like:
vector<B&> vector_objects
?

That's not allowed in C++.

That would declare a vector of references to B objects, not a "reference to
vector objects". I suspect this is what you meant, but you should be sure
of it, especially since what you wrote isn't legal C++.
If I had the following function:
void add_stuff_to_th e_vector()
{
B b;
b.foo = "Hello"
vector_objects. push_back(b);
}

Would that be ok? The push_back'd object that there's a reference to in
the vector wouldn't disappear after the function ends?


As I said above, you can't put references in a vector, so no point trying to
fill it, eh? :-)

-Howard
Mar 22 '06 #9
Howard wrote:
"Joe Van Dyk" <jo********@boe ing.com> wrote in message
news:Iw******** @news.boeing.co m...
Is there some rule of thumb about when to use pointers to an object and
when to use a reference* to an object when a class needs to have objects
as data members?

Example:
class A
{
B* b_ptr;
B b;
vector<B*> vector_ptrs;
vector<B> vector_objects;
};

How do I know when to use pointers and when not to use them?

Thanks,
Joe

* I'm not sure if my terminology is correct here, please correct me if I'm
wrong.

Your question asks about something you called "reference* ". There's no such
thing as a "reference* ". Did you just mean "reference" ?


The '*' was a footnote indicator.

Also, your example shows a B* pointer member and a B object member , and
doesn't show any reference members at all.

So I guess I'm confused as to what your question really means.
Me too. :(
I'm also slightly confused about the relationship between references and
pointers. I know a reference is an alias of an object and a pointer
contains some address that's usually the start of the object's location in
memory, but I'm still not sure what the real difference is.

A good book will help you the most here.


I'm still making my way through the good books.

-Howard

Mar 22 '06 #10

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

Similar topics

4
3867
by: Michael Wagner | last post by:
I do some Windows kernel programming, where what I need to pass to some Kernel call is "void* Context". Sometime later, I will get that Conext back. I want to pass a class pointer to this system class, and then pass the void* back to the class when the kernel calls be back. I am not clear which of the casts I really want to use in this case, though I am pretty sure that I don't want dynamic casts or const casts. Do I want static or...
4
2268
by: Brian | last post by:
Hi all, I am implementing an object that is currently using function pointers for callbacks to let me do something on assignment: template <class T> class MyClass{ private: typedef T& (* writer) (T& oldval, T& newval); writer onwrite;
14
3536
by: Roland Bengtsson | last post by:
I have a class Conception and I have this in a vector, it should be: vector<Conception> vek; // vector vector<Conception>::iterator vek; // iterator to vek But what if I want to have pointers to class Conception instead? How can I do that? And how should I write to declare an iterator to this vector?
24
2874
by: Rv5 | last post by:
Rookie c++ question, but Ive spent the last 5 years doing Java, where everytime I created an object I used new. In c++ I can create my objects without and its confusing me just a little. I have a class called polynomial. Its a nothing little class right now, with just int variables, a basic container class. Im using it as I go through some tutorials, but in this particular tutorial its telling me to do polynomial *first = new...
14
2838
by: Alf P. Steinbach | last post by:
Not yet perfect, but: http://home.no.net/dubjai/win32cpptut/special/pointers/ch_01.pdf http://home.no.net/dubjai/win32cpptut/special/pointers/ch_01_examples.zip To access the table of contents, use the "Bookmarks" tab in Adobe Acrobat. Comments, corrections, praise, nits, etc., are still welcome!
1
1893
by: Bushido Hacks | last post by:
A private utility function using a function pointer sounds ideal to me. I want to simpify writing the same set of loops. While there are a few functions that can't use it, setting and modifying values sounds ideal. I would like to know if the usage of this function pointer is valid before I refactor some of the other functions that use the same data structure to complete functions. class Object
15
2176
by: Jess | last post by:
Hello, Sometimes declarations are all what we need when we define/declare classes (or functions?), but sometimes we need definitions. I learned that if we define a class (B) that has an object (a_obj) of a class type (A), then we need to define A as well, but if B has a pointer to A, then we only need to forward declare A. I was told this is because the compiler needs to see the implemenation of A when allocating memory for a_obj. ...
32
2570
by: Joe | last post by:
I am just starting to use Object Oriented PHP coding, and I am seeing quite often the following (this example taken from a wiki): $wakka =& new Wakka($wakkaConfig); What exactly is the =&, and why is it different from = ?
8
1212
by: Rob | last post by:
I have a vector of a class type and when I create an object inside a function and return that and add it to the vector, it doesn't properly keep the data inside it. So I have a few questions: 1. Is this because it loses scope since it wasn't created with "new"? 2. If I do create it with new, but the vector holds objects not pointers, will the vector's "delete" operator function still handle deleting all those pointers? CODE 1:
0
9647
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9492
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10360
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
10163
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...
0
9960
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...
1
7510
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5532
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4064
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2894
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.