When to use pointers in a class?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Joe Van Dyk

    #1

    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.
  • Phlip

    #2
    Re: When to use pointers in a class?

    Joe Van Dyk wrote:
    [color=blue]
    > 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?[/color]

    Prefer a reference unless you need a pointer's extra features.
    [color=blue]
    > Example:
    > class A
    > {
    > B* b_ptr;[/color]

    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.
    [color=blue]
    > B b;
    > vector<B*> vector_ptrs;[/color]

    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.
    [color=blue]
    > vector<B> vector_objects;[/color]

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

    The simpler the better.
    [color=blue]
    > * 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.[/color]

    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!!!

    Comment

    • Howard

      #3
      Re: When to use pointers in a class?


      "Phlip" <phlip2005@gmai l.com> wrote in message
      news:35%Tf.56$m u2.39@newssvr24 .news.prodigy.n et...[color=blue]
      > Joe Van Dyk wrote:
      >[color=green]
      >> 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?[/color]
      >
      > Prefer a reference unless you need a pointer's extra features.[/color]

      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.
      [color=blue]
      >[color=green]
      >> Example:
      >> class A
      >> {
      >> B* b_ptr;[/color]
      >
      > Prefer a reference (seated in A::A), unless you need b_ptr==NULL for
      > special
      > situations.[/color]

      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.
      [color=blue]
      >
      > 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.
      >[color=green]
      >> B b;
      >> vector<B*> vector_ptrs;[/color]
      >
      > 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.
      >[color=green]
      >> vector<B> vector_objects;[/color]
      >
      > That is a copy, not a reference. Prefer one, if B is cleanly copiable, in
      > preference to pointers _or_ references.[/color]

      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


      Comment

      • Phlip

        #4
        Re: When to use pointers in a class?

        Howard wrote:
        [color=blue][color=green]
        >> Prefer a reference unless you need a pointer's extra features.[/color]
        >
        > As a data member? Why? I rarely use references as members.[/color]

        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.
        [color=blue]
        > 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.[/color]

        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!
        [color=blue]
        > I don't understand. You mean you'd prefer
        >
        > class A
        > {
        > B& b;
        > //...
        > };
        >
        > over
        >
        > class A
        > {
        > B b;
        > //...
        > };
        >
        > ...?[/color]

        If A can own the B, use the last one. It's the _weakest_ construction, with
        the _least_ extra features.
        [color=blue]
        > 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.[/color]

        I did. I ass-u-me-d that the OP knew to prefer member objects over handles
        of any kind.
        [color=blue]
        > 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.[/color]

        When you need the extra features pointers provide, use them.
        [color=blue]
        > Smart pointers as vector members, I am told, are an even better solution
        > in many cases.[/color]

        If they are indeed smart enough ;-)

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

        Comment

        • loufoque

          #5
          Re: When to use pointers in a class?

          Joe Van Dyk wrote :[color=blue]
          > 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?[/color]

          If you don't need pointers, dont use pointers.

          Comment

          • Joe Van Dyk

            #6
            Re: When to use pointers in a class?

            Phlip wrote:[color=blue]
            > Joe Van Dyk wrote:
            >
            >[color=green]
            >>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?[/color]
            >
            >
            > Prefer a reference unless you need a pointer's extra features.[/color]

            In which situations would I want a pointer's extra features, and what
            are those extra features?
            [color=blue][color=green]
            >>Example:
            >>class A
            >>{
            >> B* b_ptr;[/color]
            >
            >
            > Prefer a reference (seated in A::A), unless you need b_ptr==NULL for special
            > situations.[/color]

            By "seated in A::A", you mean put into A's constructor?
            [color=blue]
            >
            > 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.
            >
            >[color=green]
            >> B b;
            >> vector<B*> vector_ptrs;[/color]
            >
            >
            > 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.
            >
            >[color=green]
            >> vector<B> vector_objects;[/color]
            >
            >
            > That is a copy, not a reference. Prefer one, if B is cleanly copiable, in
            > preference to pointers _or_ references.[/color]

            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?
            [color=blue]
            >
            > The simpler the better.
            >
            >[color=green]
            >>* 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.[/color]
            >
            >
            > 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.[/color]

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

            Thanks, you've been quite helpful!

            Joe

            Comment

            • Howard

              #7
              Re: When to use pointers in a class?


              "Joe Van Dyk" <joe.vandyk@boe ing.com> wrote in message
              news:IwHzGJ.EqD @news.boeing.co m...[color=blue]
              > 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.[/color]

              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.

              [color=blue]
              > 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.[/color]

              A good book will help you the most here.

              -Howard



              Comment

              • Simon Elliott

                #8
                Re: When to use pointers in a class?

                On 21/03/2006, Joe Van Dyk wrote:
                [color=blue]
                > 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?
                >[/color]

                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

                Comment

                • Howard

                  #9
                  Re: When to use pointers in a class?


                  "Joe Van Dyk" <joe.vandyk@boe ing.com> wrote in message
                  news:IwI3Fz.KDG @news.boeing.co m...[color=blue]
                  > Phlip wrote:[color=green]
                  >> Joe Van Dyk wrote:
                  >>
                  >>[color=darkred]
                  >>>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?[/color]
                  >>
                  >>
                  >> Prefer a reference unless you need a pointer's extra features.[/color]
                  >
                  > In which situations would I want a pointer's extra features, and what are
                  > those extra features?[/color]

                  I mentioned two reasons in my post earlier in this sub-thread.


                  [color=blue]
                  > Would a reference to vector objects look like:
                  > vector<B&> vector_objects
                  > ?
                  >[/color]

                  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++.
                  [color=blue]
                  > 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?
                  >[/color]

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

                  -Howard


                  Comment

                  • Joe Van Dyk

                    #10
                    Re: When to use pointers in a class?

                    Howard wrote:[color=blue]
                    > "Joe Van Dyk" <joe.vandyk@boe ing.com> wrote in message
                    > news:IwHzGJ.EqD @news.boeing.co m...
                    >[color=green]
                    >>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.[/color]
                    >
                    >
                    > Your question asks about something you called "reference* ". There's no such
                    > thing as a "reference* ". Did you just mean "reference" ?[/color]

                    The '*' was a footnote indicator.
                    [color=blue]
                    >
                    > 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.[/color]

                    Me too. :(
                    [color=blue][color=green]
                    >> 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.[/color]
                    >
                    >
                    > A good book will help you the most here.[/color]

                    I'm still making my way through the good books.
                    [color=blue]
                    >
                    > -Howard
                    >
                    >
                    >[/color]

                    Comment

                    • Joe Van Dyk

                      #11
                      Re: When to use pointers in a class?

                      Joe Van Dyk wrote:[color=blue]
                      > 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?[/color]

                      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

                      Comment

                      • Joe Van Dyk

                        #12
                        Re: When to use pointers in a class?

                        Joe Van Dyk wrote:[color=blue]
                        > Joe Van Dyk wrote:
                        >[color=green]
                        >> 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?[/color]
                        >
                        >
                        > 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;[/color]

                        oops
                        Magick::Geometr y &_geometry;

                        [color=blue]
                        > 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[/color]

                        Comment

                        • Daniel T.

                          #13
                          Re: When to use pointers in a class?

                          In article <IwHzGJ.EqD@new s.boeing.com>,
                          Joe Van Dyk <joe.vandyk@boe ing.com> wrote:
                          [color=blue]
                          > 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?[/color]

                          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.

                          Comment

                          • Phlip

                            #14
                            Re: When to use pointers in a class?

                            Daniel T. wrote:
                            [color=blue]
                            > As member-variables: prefer by-value.[/color]

                            Except when indulging in "encapsulat ion construction". ;-)

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


                            Comment

                            • Phlip

                              #15
                              Re: When to use pointers in a class?

                              >> As member-variables: prefer by-value.[color=blue]
                              >
                              > Except when indulging in "encapsulat ion construction". ;-)[/color]

                              Uh, "constructi on encapsulation". ..
                              [color=blue]
                              >
                              > --
                              > Phlip
                              > http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
                              >[/color]


                              Comment

                              Working...