Reputation: 33
I was going through following code:
#include <iostream>
using namespace std;
class B
{
public:
int a;
void display()
{
a=10;
cout<<"Content of base class.\n"; }
};
int main()
{
B *b,b1,b2;
char *a=new char[1];
*a='A';
if(b==NULL)
{
cout<<(*(int*)a)<<endl;
}
b->display();
b1.display();
b2.display();
b->a=60;
b1.a=40;
b2.a=50;
cout<<b->a<<endl<<b1.a<<endl<<b2.a;
return 0;
}
It is giving the following output:
65
Content of base class.
Content of base class.
Content of base class.
60
40
50
According to my knowledge for every object created some space is allocated and the data of that object is stored there(Here b1 and b2).But in this code b is just a pointer and still it is able to access function and variables of class B and it is not even pointing any object of class B.b is NULL as indicated by if statement.I am getting confused with this!!!
Now I also want to know where b->a (whose value is 60) is stored?Like 40 and 50 will be there in b1 and b2.
Also, if only pointers are sufficient to call the functions then is it really necessary to create objects everytime?
Upvotes: 0
Views: 82
Reputation: 3657
Considering your running what you have there: (unified diff: http://hastebin.com/midocuqiki), you will get:
$ ./b
Segmentation fault (core dumped)
actually, when you compile:
$ g++ -Wall B.cpp -o b
B.cpp: In function ‘int main()’:
B.cpp:11:5: warning: ‘b’ may be used uninitialized in this function [-Wmaybe-uninitialized]
if(b==NULL)
^
It is undefined behavior. You got that output, because Visual Studio (and that's what I think you use), is optimizing to use your previous stack and you're going to the same location in memory where you actually have something.
But is completely wrong!
and YES, it is "really necessary to create objects every time" !
UPDATE: @codecracker says this behavior is on gcc
as well! (weird)
Upvotes: 0
Reputation: 31647
b->display();
yields undefined behavior. That means, whatever your computer does at that moment is good enough.
The question of where b->a
is stored makes no sense, because accessing b->a
yields undefined behavior.
In some cases, C++ is not obliged to tell you that you screwed it up. Dereferencing a pointer to uninitialized memory is such a case.
Upvotes: 2
Reputation: 27528
It's undefined behaviour. The output you received, and the fact that the program did not crash, is nothing but a coincidence.
If you don't need an object, use static or free-standing functions.
Upvotes: 3