473,385 Members | 1,764 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

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 2082
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*******@gmail.com> wrote in message
news:35*************@newssvr24.news.prodigy.net...
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_the_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********@boeing.com> wrote in message
news:Iw********@news.boeing.com...
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********@boeing.com> wrote in message
news:Iw********@news.boeing.com...
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_the_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********@boeing.com> wrote in message
news:Iw********@news.boeing.com...
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
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?


Related question:

I have a class that looks like this:
class Image
{
public:
typedef unsigned int color_type;
Image(size_t width, size_t height);
void write(const std::string& image_file_name);
void set_pixel(size_t x, size_t y,
color_type r, color_type g, color_type b);

private:
Magick::Image &_image;
Magick::Geometry &(geometry;
Magick::ColorRGB &_background_color;
};

(documentation on ImageMagick++ is at
http://www.simplesystems.org/Magick+...mentation.html)

Quick overview: a Magick::Image takes in its constructor a Geometry and
a Color. A Magick::Geometry takes in its constructor a width and a
height. And the Magick::ColorRGB object takes nothing in its constructor.

Do I want to use references to the member objects here? Or pointers?
I'm having difficulties initializing the objects if they are references
and aren't passed in to the Image constructor.

Thanks,
Joe
Mar 22 '06 #11
Joe Van Dyk 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?

Related question:

I have a class that looks like this:
class Image
{
public:
typedef unsigned int color_type;
Image(size_t width, size_t height);
void write(const std::string& image_file_name);
void set_pixel(size_t x, size_t y,
color_type r, color_type g, color_type b);

private:
Magick::Image &_image;
Magick::Geometry &(geometry;


oops
Magick::Geometry &_geometry;

Magick::ColorRGB &_background_color;
};

(documentation on ImageMagick++ is at
http://www.simplesystems.org/Magick+...mentation.html)

Quick overview: a Magick::Image takes in its constructor a Geometry and
a Color. A Magick::Geometry takes in its constructor a width and a
height. And the Magick::ColorRGB object takes nothing in its constructor.

Do I want to use references to the member objects here? Or pointers?
I'm having difficulties initializing the objects if they are references
and aren't passed in to the Image constructor.

Thanks,
Joe

Mar 22 '06 #12
In article <Iw********@news.boeing.com>,
Joe Van Dyk <jo********@boeing.com> 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?


Think of a reference as a const pointer that can't be NULL, and uses
object syntax. IE:

B& rb;
B* const pb;

Are very much alike in their behavior. For rb you do "rb.someFunc()" for
pb you do "pb->someFuc()"

Here are some basic rules of thumb...

As member-variables: prefer by-value. If you need to hold something that
is being shared among several objects, then use a pointer. If you need
to hold something that is an Abstract Base Class (ABC) then use a
pointer.

A vector template defines a vector's member-variables so use the same
rule as above for making one. IE prefer vector<B> unless the things
contained in the vector are being shared or B is an abstract base class.
--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.
Mar 22 '06 #13
Daniel T. wrote:
As member-variables: prefer by-value.


Except when indulging in "encapsulation construction". ;-)

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
Mar 22 '06 #14
>> As member-variables: prefer by-value.

Except when indulging in "encapsulation construction". ;-)
Uh, "construction encapsulation"...

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!

Mar 22 '06 #15

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?


One important thing to keep in mind is that if a class contains a
reference, then instances of it cannot be contained in an STL
container*. It is not always easy to know when you're designing the
class if this is something you'll need to do in the future or not.

* Assuming there isn't an assignment operator that doesn't touch the
reference.

Mar 22 '06 #16
"Joe Van Dyk" <jo********@boeing.com> wrote in message
news:Iw********@news.boeing.com...
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.


I would say use a pointer if you need polymorphism. You can't get
polymorphism through a reference (my understanding anyway). Also, you can
reassign a pointer, you can't reassign a reference. The reference needs to
be set in the constructor initialization list, so the object being
referenced has to exist before the consturctor.
Mar 22 '06 #17

"Jim Langston" <ta*******@rocketmail.com> wrote in message
news:sW***************@fe03.lga...

I would say use a pointer if you need polymorphism. You can't get
polymorphism through a reference (my understanding anyway).
Yes, you can. Polymorphism doesn't come into play when making calls
directly on an object's methods, but it does when making calls on the object
through a pointer or reference to it.
Also, you can reassign a pointer, you can't reassign a reference. The
reference needs to be set in the constructor initialization list, so the
object being referenced has to exist before the consturctor.


-Howard
Mar 22 '06 #18
Jim Langston wrote:
"Joe Van Dyk" <jo********@boeing.com> wrote in message
news:Iw********@news.boeing.com...
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.

I would say use a pointer if you need polymorphism. You can't get
polymorphism through a reference (my understanding anyway). Also, you can
reassign a pointer, you can't reassign a reference. The reference needs to
be set in the constructor initialization list, so the object being
referenced has to exist before the consturctor.

Yes you can get polymorphism through a reference.

If the object being referenced exists when the container is constructed,
knowing the object is there saves the code form checking a pointer for
NULL.

If the contained object can be replaced, then yes, use a pointer.
--
Ian Collins.
Mar 22 '06 #19
"Howard" <al*****@hotmail.com> wrote in message
news:W8******************@bgtnsc04-news.ops.worldnet.att.net...

"Jim Langston" <ta*******@rocketmail.com> wrote in message
news:sW***************@fe03.lga...

I would say use a pointer if you need polymorphism. You can't get
polymorphism through a reference (my understanding anyway).


Yes, you can. Polymorphism doesn't come into play when making calls
directly on an object's methods, but it does when making calls on the
object through a pointer or reference to it.
Also, you can reassign a pointer, you can't reassign a reference. The
reference needs to be set in the constructor initialization list, so the
object being referenced has to exist before the consturctor.


-Howard


Wow, you're right. My understanding was wrong. The output of the following
program is "derived".

#include <iostream>
#include <string>

class base
{
public:
virtual method() { std::cout << "base" << std::endl; }
};

class derived: public base
{
public:
method() { std::cout << "derived" << std::endl; }
};

int main ()
{
derived MyDerived;
base& baseref = MyDerived;
baseref.method();

std::string wait;
std::cin >> wait;
}
Mar 23 '06 #20
I V
Joe Van Dyk wrote:
class Image
{
public:
typedef unsigned int color_type;
Image(size_t width, size_t height);
It looks like Magick++ uses unsigned int, rather than size_t for height
and width specifications. Maybe your application ought to use the same?

[...]
Do I want to use references to the member objects here? Or pointers?
I'm having difficulties initializing the objects if they are references
and aren't passed in to the Image constructor.


Do you need to store the Geometry and ColorRGB objects at all? If
they're only being used as arguments to the Magick::Image constructor,
they can probably be local variables in your Image constructor.
Otherwise, you probably want to store the actual objects in your class
- neither reference nor pointer.

If the Magick::Image object has the same lifetime as your Image class,
then you probably want to store it directly in your class (again,
neither pointer nor reference). If the Magick::Image object is created
at some point after your Image object, or will be destroyed sometime
before your Image object, you should use a pointer.

Mar 23 '06 #21

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

Similar topics

4
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...
4
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& (*...
14
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...
24
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...
14
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...
1
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...
15
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...
32
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...
8
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....
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...

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.