"has-a" question

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Leo

    #1

    "has-a" question

    Dear All,

    Can I do this:

    class MyClass()
    {
    public:
    doStuff();
    private:
    int iNum;
    };

    MyClass::doStuf f()
    {
    MyClass obj; //Is this ok? Has a object inside itself?
    cout << obj.iNum << endl;
    }

    Thank you very much.

  • GB

    #2
    Re: &quot;has-a&quot; question

    Leo wrote:[color=blue]
    > Dear All,
    >
    > Can I do this:
    >
    > class MyClass()
    > {
    > public:
    > doStuff();
    > private:
    > int iNum;
    > };
    >
    > MyClass::doStuf f()
    > {
    > MyClass obj; //Is this ok? Has a object inside itself?
    > cout << obj.iNum << endl;
    > }
    >
    > Thank you very much.
    >[/color]

    Yes. The object is not however inside itself. It exists only for the
    duration of the execution of Myclass::doStuf f as a separate object from
    the one on which MyClass::doStuf f is being called (i.e., *this is one
    object, and obj is another independent one.

    Gregg

    Comment

    • Peter_Julian

      #3
      Re: &quot;has-a&quot; question


      "Leo" <xxx@nospam.com > wrote in message
      news:dps7pn$38e u$1@osf1.gmu.ed u...
      | Dear All,
      |
      | Can I do this:
      |
      | class MyClass()
      | {
      | public:
      | doStuff();
      | private:
      | int iNum;
      | };
      |
      | MyClass::doStuf f()
      | {
      | MyClass obj; //Is this ok? Has a object inside itself?
      | cout << obj.iNum << endl;
      | }
      |
      | Thank you very much.
      |

      That should have been:
      #include <iostream>
      #include <ostream>

      class MyClass
      {
      int iNum;
      public:
      void doStuff();
      };

      void MyClass::doStuf f()
      {
      MyClass obj;
      std::cout << obj.iNum << std::endl; // iNum == garbage
      }

      You won't get what you expect. the private variable iNum is unitialized
      since you are generating a local instance of a MyClass object and no
      default ctor has been defined that initializes its internals. Hence the
      garbage.

      Now consider:

      #include <iostream>
      #include <ostream>

      class MyClass
      {
      int n;
      public:
      /* ctor */
      MyClass() : n(0) { } // default ctor
      MyClass(int i) : n(i) { }
      /* d~tor */
      ~MyClass() { }
      /* member function */
      int getN() const;
      };

      int MyClass::getN() const
      {
      return n;
      }

      int main()
      {
      MyClass myclass;
      std::cout << myclass.getN() << std::endl; // prints 0, not garbage

      MyClass myclass2(99);
      std::cout << myclass2.getN() << std::endl; // prints 99

      return 0;
      }

      No more garbage.




      Comment

      Working...