CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Sep 2010
    Posts
    2

    Unhappy Difference between object creation on stack and on heap

    Hi All,

    Is there any difference in the way object is created on stack and on heap?

    I have come across a strange problem. Code snippet is as follows:

    class A
    {
    private:
    int a;
    float b;
    char c;

    void Print()
    {
    cout<<"a = "<<a<<" b = "<<b<<" c = "<<c<<endl;
    }
    };

    When I use
    A *a = new A;
    a->Print();
    it compiles and prints some garbage values(as expected), which is fine.

    But when I use
    A a;
    a.Print();
    it gives compilation errors 1. 'a.A::a' is used uninitialized in this function 2. 'a.A::b' is used uninitialized in this function 3. 'a.A::c' is used uninitialized in this function

    Can anyone please explain why is this happening??

    Thanks

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Difference between object creation on stack and on heap

    Those aren't errors, they're warnings.

    Basically, in both cases *you* know that the values will be garbage, but the compiler is only flagging one of them for you. It's perfectly fine for it to flag both cases, or neither; it's just trying to tell you that you're doing something you probably didn't intend to do (print out garbage values).

  3. #3
    Join Date
    Jan 2009
    Posts
    1,689

    Re: Difference between object creation on stack and on heap

    Do you have -Werror in your compile options? Lindley is half right, those are supposed to be warnings. The -Werror option will cause them to show up as errors.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured