|
-
September 8th, 2010, 05:44 AM
#1
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
-
September 8th, 2010, 06:12 AM
#2
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).
-
September 8th, 2010, 07:55 AM
#3
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|