473,799 Members | 3,081 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
20 2130
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::Geometr y &(geometry;
Magick::ColorRG B &_background_co lor;
};

(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::Geometr y takes in its constructor a width and a
height. And the Magick::ColorRG B 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::Geometr y &(geometry;


oops
Magick::Geometr y &_geometry;

Magick::ColorRG B &_background_co lor;
};

(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::Geometr y takes in its constructor a width and a
height. And the Magick::ColorRG B 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********@new s.boeing.com>,
Joe Van Dyk <jo********@boe ing.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.someFun c()" 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 "encapsulat ion construction". ;-)

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

Except when indulging in "encapsulat ion construction". ;-)
Uh, "constructi on 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********@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. 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*******@rock etmail.com> wrote in message
news:sW******** *******@fe03.lg a...

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********@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. 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*****@hotmai l.com> wrote in message
news:W8******** **********@bgtn sc04-news.ops.worldn et.att.net...

"Jim Langston" <ta*******@rock etmail.com> wrote in message
news:sW******** *******@fe03.lg a...

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

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

Similar topics

4
3868
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
2876
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
2839
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
1894
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
2571
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
1214
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
9686
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
9540
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
10475
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
10026
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
9068
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...
1
7564
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
6805
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
5585
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4139
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

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.