question about objects passed into constructors

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • fighter1@airmail.net

    question about objects passed into constructors

    Hello,

    I have a question about passing an object into a constructor.

    How can I check to make sure that the object is good/valid that is
    being passed into the constructor.

    Obviously I could check to see if it is non-NULL, but that still will
    not necessarily tell me anything.

    For example:

    /* here is a constructor car that takes an engine class as an
    argument. But, I better check to make sure that engine is valid
    so how do I do that?
    */
    Car::Car( Engine* engine )
    {

    // check to make sure that engine is valid.


    }


    Thanks in advance for any help,
    John
  • Donovan Rebbechi

    #2
    Re: question about objects passed into constructors

    In article <j2oe009jbf1fob fm3undhnom2lb1v q4l12@4ax.com>, fighter1@airmai l.net wrote:
    [color=blue]
    > How can I check to make sure that the object is good/valid that is
    > being passed into the constructor.
    >
    > Obviously I could check to see if it is non-NULL, but that still will
    > not necessarily tell me anything.
    >
    > For example:
    >
    > /* here is a constructor car that takes an engine class as an
    > argument. But, I better check to make sure that engine is valid
    > so how do I do that?
    > */[/color]

    What do you mean by "valid" ? The Engine class should be responsible for making
    sure that Engine objects are not "invalid".

    Since you are passing in a pointer, you need to check for a null pointer.

    If the pointer is not null, it's the callers responsibility to pass in a valid
    pointer. There's no way to check whether a pointer is "wild" or not.

    Cheers,
    --
    Donovan Rebbechi

    Comment

    • David White

      #3
      Re: question about objects passed into constructors

      <fighter1@airma il.net> wrote in message
      news:j2oe009jbf 1fobfm3undhnom2 lb1vq4l12@4ax.c om...[color=blue]
      > Hello,
      >
      > I have a question about passing an object into a constructor.
      >
      > How can I check to make sure that the object is good/valid that is
      > being passed into the constructor.
      >
      > Obviously I could check to see if it is non-NULL,[/color]

      Unless it's a pointer there's nothing to check, NULL-wise.
      [color=blue]
      > but that still will
      > not necessarily tell me anything.
      >
      > For example:
      >
      > /* here is a constructor car that takes an engine class as an
      > argument. But, I better check to make sure that engine is valid
      > so how do I do that?
      > */
      > Car::Car( Engine* engine )
      > {
      >
      > // check to make sure that engine is valid.[/color]

      You'll have to ask the Engine object, if it has a member that serves that
      purposes. Other than checking whether the supposed memory the object
      occupies is real memory, which is a system-specific matter and OT here,
      there is no general way to tell if an object is valid. If the Engine itself
      can't tell you it's valid, nothing else can.

      DW



      Comment

      • E. Robert Tisdale

        #4
        Re: question about objects passed into constructors

        fighter1@airmai l.net wrote:
        [color=blue]
        > I have a question about passing an object into a constructor.
        >
        > How can I check to make sure that
        > the object that is being passed into the constructor is good/valid.
        >
        > Obviously I could check to see if it is non-NULL
        > but that still will not necessarily tell me anything.[/color]


        class Engine {
        private:
        // representation
        const
        unsigned int Valid;
        public:
        //functions
        bool valid(void) const {
        return 0x55555555 == Valid;
        }
        // constructors
        Engine(void): Valid(0x5555555 5) { }
        ~Engine(void) { Valid = 0xAAAAAAAA; }
        };
        [color=blue]
        > For example:
        >
        > // Here is a constructor car
        > // that takes an engine class as an argument.
        > // I had better check to make sure that engine is valid.
        > // How do I do that?
        >
        > Car::Car(const Engine& engine) {
        > // check to make sure that engine is valid.
        > if (engine.valid() ) {
        > // Initialize *this.
        > }
        > else { /* Handle error. */ }
        > }[/color]

        Comment

        • David White

          #5
          Re: question about objects passed into constructors

          "E. Robert Tisdale" <E.Robert.Tisda le@jpl.nasa.gov > wrote in message
          news:40076644.5 030700@jpl.nasa .gov...[color=blue]
          > fighter1@airmai l.net wrote:
          >[color=green]
          > > I have a question about passing an object into a constructor.
          > >
          > > How can I check to make sure that
          > > the object that is being passed into the constructor is good/valid.
          > >
          > > Obviously I could check to see if it is non-NULL
          > > but that still will not necessarily tell me anything.[/color]
          >
          >
          > class Engine {
          > private:
          > // representation
          > const
          > unsigned int Valid;
          > public:
          > //functions
          > bool valid(void) const {
          > return 0x55555555 == Valid;
          > }
          > // constructors
          > Engine(void): Valid(0x5555555 5) { }
          > ~Engine(void) { Valid = 0xAAAAAAAA; }
          > };[/color]

          Of course, with the same "valid" value used in all instances, and perhaps in
          other classes as well, it will greatly increase the probability that some
          dangling or uninitialized pointer will be unlucky enough to point somewhere
          such that the Valid member happens to be 0x55555555.

          DW



          Comment

          • Peter Koch Larsen

            #6
            Re: question about objects passed into constructors


            <fighter1@airma il.net> skrev i en meddelelse
            news:j2oe009jbf 1fobfm3undhnom2 lb1vq4l12@4ax.c om...[color=blue]
            > Hello,
            >
            > I have a question about passing an object into a constructor.
            >
            > How can I check to make sure that the object is good/valid that is
            > being passed into the constructor.
            >
            > Obviously I could check to see if it is non-NULL, but that still will
            > not necessarily tell me anything.
            >
            > For example:
            >
            > /* here is a constructor car that takes an engine class as an
            > argument. But, I better check to make sure that engine is valid
            > so how do I do that?
            > */
            > Car::Car( Engine* engine )
            > {
            >
            > // check to make sure that engine is valid.
            >
            >
            > }
            >
            >
            > Thanks in advance for any help,
            > John[/color]


            Most probably, you need to not use a pointer:

            Car::Car(Engine const& engine)

            as this will assure a proper engine-object to be passed always.

            If "Car" does not need an engine, you could keep your present design.

            If Car needs to use an engine, but you for some reason want to keep the
            signature of the constructor (the reason for this would not be based in the
            language), You should throw from the constructor:

            Car::Car( Engine* engine)
            {
            if (!engine) throw 0; // have a proper exception here!!
            // continue construction here
            }

            but be prepared to refactor later.

            I can't really recommend Tisdales trick unless there is a compelling reason
            to do it that way (e.g. if you are not allowed to throw an exception in the
            constructor).

            /Peter


            Comment

            • Chris Theis

              #7
              Re: question about objects passed into constructors


              <fighter1@airma il.net> wrote in message
              news:j2oe009jbf 1fobfm3undhnom2 lb1vq4l12@4ax.c om...[color=blue]
              > Hello,
              >
              > I have a question about passing an object into a constructor.
              >
              > How can I check to make sure that the object is good/valid that is
              > being passed into the constructor.
              >
              > Obviously I could check to see if it is non-NULL, but that still will
              > not necessarily tell me anything.
              >[/color]
              [SNIP]

              Well, the whole problem arises from the word "valid". It depends very much
              what you define as a valid object. Testing for NULL is a way of checking
              whether a pointer is valid but this doesn't tell you whether the object,
              which this pointer points to, has a "valid = reasonable" state. If you just
              want to check whether the pointer has something to point to then this NULL
              test is fine. Otherwise you will have to define what characterizes a
              "good/valid" object state and supply some function to check this. (See
              Robert Tisdale's post).

              Cheers
              Chris


              Comment

              • Dag Henriksson

                #8
                Re: question about objects passed into constructors

                <fighter1@airma il.net> skrev i meddelandet
                news:j2oe009jbf 1fobfm3undhnom2 lb1vq4l12@4ax.c om...[color=blue]
                > Hello,
                >
                > I have a question about passing an object into a constructor.
                >
                > How can I check to make sure that the object is good/valid that is
                > being passed into the constructor.[/color]

                Why would you like to do that?
                IMHO the right way to do it is that in the documentation of the class say
                something as:

                Car::Car( Engine* engine )
                Precondition: engine points to a valid Engine object.

                and leave the responsibility for this to the caller. This is the approach
                the standard library has.

                For example:
                18.6.2.3 set_unexpected
                unexpected_hand ler set_unexpected( unexpected_hand ler f) throw();
                1 Effects: Establishes the function designated by fas the current
                unexpected_hand ler.
                2 Requires: f shall not be a null pointer.

                --
                Dag Henriksson


                Comment

                • Daniel T.

                  #9
                  Re: question about objects passed into constructors

                  In article <j2oe009jbf1fob fm3undhnom2lb1v q4l12@4ax.com>,
                  fighter1@airmai l.net wrote:
                  [color=blue]
                  > Hello,
                  >
                  > I have a question about passing an object into a constructor.
                  >
                  > How can I check to make sure that the object is good/valid that is
                  > being passed into the constructor.
                  >
                  > Obviously I could check to see if it is non-NULL, but that still will
                  > not necessarily tell me anything.
                  >
                  > For example:
                  >
                  > /* here is a constructor car that takes an engine class as an
                  > argument. But, I better check to make sure that engine is valid
                  > so how do I do that?
                  > */
                  > Car::Car( Engine* engine )
                  > {
                  >
                  > // check to make sure that engine is valid.
                  >
                  >
                  > }[/color]

                  In other words, you want to guard against someone doing something like:

                  Car myCar( (Engine*) 0x543562 );

                  (where 0x543562 doesn't point to an actual Engine object.) Or some such?

                  There isn't much you can do about this, but here is one idea:

                  class Engine {
                  static std::set< Engine* > allEngines;
                  public:
                  static bool isValid( Engine* anEngine ) {
                  return allEngines.coun t( anEngine ) == 1;
                  }

                  Engine() {
                  allEngines.inse rt( this );
                  }
                  ~Engine() {
                  allEngines.eras e( this );
                  }
                  };

                  Now:

                  Car::Car( Engine* engine ) {
                  assert( Engine::isValid ( engine ) );
                  //...
                  }

                  This is not a cheep operation! It will probably slow your program down
                  tremondusly if you do this with every class. Be sure to make it so you
                  can define the extra code out when you build a release version.

                  Comment

                  • Dag Henriksson

                    #10
                    Re: question about objects passed into constructors


                    "Daniel T." <postmaster@eat hlink.net> skrev i meddelandet
                    news:postmaster-29D8B8.08400116 012004@news02.e ast.earthlink.n et...[color=blue]
                    > In other words, you want to guard against someone doing something like:
                    >
                    > Car myCar( (Engine*) 0x543562 );
                    >
                    > (where 0x543562 doesn't point to an actual Engine object.) Or some such?
                    >
                    > There isn't much you can do about this, but here is one idea:[/color]

                    Your idea will probably work on some implementation, but technically is the
                    effect of using an invalid pointer value undefined and could cause a
                    system-generated runtime fault.

                    That means that you can not check if a pointer argument is valid or not
                    inside a function (or anywhere else). When the pointer is passed to the
                    function (by value) we have already invoked undefined behavior.

                    --
                    Dag Henriksson


                    Comment

                    • jeffc

                      #11
                      Re: question about objects passed into constructors


                      "Peter Koch Larsen" <pkl@mailme.d k> wrote in message
                      news:4007a96a$0 $247$edfadb0f@d read14.news.tel e.dk...[color=blue]
                      > If Car needs to use an engine, but you for some reason want to keep the
                      > signature of the constructor (the reason for this would not be based in[/color]
                      the[color=blue]
                      > language), You should throw from the constructor:
                      >
                      > Car::Car( Engine* engine)
                      > {
                      > if (!engine) throw 0; // have a proper exception here!!
                      > // continue construction here
                      > }
                      >
                      > but be prepared to refactor later.
                      >
                      > I can't really recommend Tisdales trick unless there is a compelling[/color]
                      reason[color=blue]
                      > to do it that way (e.g. if you are not allowed to throw an exception in[/color]
                      the[color=blue]
                      > constructor).[/color]

                      Yeah, but there is also the requirement that the pointer is "good/valid".
                      Depending on what the OP meant, your check doesn't guarantee that either.


                      Comment

                      • E. Robert Tisdale

                        #12
                        Re: question about objects passed into constructors

                        Chris Theis wrote:
                        [color=blue]
                        > Well, the whole problem arises from the word "valid".
                        > It depends very much what you define as a valid object.
                        > Testing for NULL is a way of checking whether a pointer is valid
                        > but this doesn't tell you whether the object to which
                        > this pointer points has a "valid = reasonable" state.
                        > If you just want to check
                        > whether the pointer has something to point to,
                        > then this NULL test is fine.
                        > Otherwise, you will need to define
                        > what characterizes a "good/valid" object state
                        > and supply some function to check this.
                        > (See Robert Tisdale's post).[/color]

                        A NULL pointer is valid pointer which always points to
                        an invalid object of any type.
                        There is, unfortunately, *no* way to determine whether
                        any other pointer (valid or not) references a valid object.
                        If every attempt to access an invalid object through a pointer
                        resulted in a segmentation fault, a bus error
                        or some other system error, there would be no problem.
                        The problem is that your program may access
                        and, perhaps, corrupt other valid data in your program.
                        It may also access an object that you have already deleted
                        but which has not been reallocated and reinitialized
                        so you must stamp it with a bit pattern which marks it invalid
                        when the program calls your constructor.

                        Comment

                        • puppet_sock@hotmail.com

                          #13
                          Re: question about objects passed into constructors

                          "Dag Henriksson" <dag.henriksson @quidsoft.se> wrote in message news:<bu8suq$e6 4hs$1@ID-200546.news.uni-berlin.de>...
                          [snip of a "registerin g new'ed objects" system][color=blue]
                          > Your idea will probably work on some implementation, but technically is the
                          > effect of using an invalid pointer value undefined and could cause a
                          > system-generated runtime fault.
                          >
                          > That means that you can not check if a pointer argument is valid or not
                          > inside a function (or anywhere else). When the pointer is passed to the
                          > function (by value) we have already invoked undefined behavior.[/color]

                          Is it still undefined behaviour if I never dereference the pointer?
                          I agree it is certainly undefined if I try to access memory an
                          invalid pointer points at as though it were valid. But simply passing
                          an invalid pointer value through a function call is undefined?
                          Just checking...
                          Socks

                          Comment

                          • Ron Natalie

                            #14
                            Re: question about objects passed into constructors


                            <puppet_sock@ho tmail.com> wrote in message news:c7976c46.0 401161306.64576 772@posting.goo gle.com...
                            [color=blue]
                            >
                            > Is it still undefined behaviour if I never dereference the pointer?
                            > I agree it is certainly undefined if I try to access memory an
                            > invalid pointer points at as though it were valid. But simply passing
                            > an invalid pointer value through a function call is undefined?
                            > Just checking...[/color]

                            Yes it is. It's possible (though I've never seen a machine where this
                            happens) where merely copying an out of range pointer might trap.

                            Comment

                            • E. Robert Tisdale

                              #15
                              Re: question about objects passed into constructors

                              Dag Henriksson wrote:
                              [color=blue]
                              > Your idea will probably work on some implementation, but technically is the
                              > effect of using an invalid pointer value undefined and could cause a
                              > system-generated runtime fault.
                              >
                              > That means that you can not check if a pointer argument is valid or not
                              > inside a function (or anywhere else). When the pointer is passed to the
                              > function (by value) we have already invoked undefined behavior.[/color]

                              I think that you missed the point.
                              A system-generated runtime fault can be trapped
                              and your program can recover or abort.
                              The problem occurs when no fault is generated
                              and your program initializes a Car object with an invalid Engine object.

                              Comment

                              Working...