: Hello all.
:
: I've been learning C++ language for some time now and I think I already know the basics of the language. There's however one little detail I'd like more information on. I would appreciate a lot if someone could shed some light on this issue.
:
: The question is about rules governing the initialization of pointers to objects in two specific cases.
:
: My first case is when the pointer variable falls in the 'automatic' storage category, e.g. when introduced locally to a function. To what value is the pointer initialized, when the type of the pointed-to thing is an instance of a class. Until recently I've been under the impression that pointers aren't initialized at all, but now it seems that they actually are. Please consider the following code snippet.
:
:
: #include <iostream>
: class ClassA
: {
:
: public:
: ClassA(){}
: virtual ~ClassA(){}
: void test(){std::cout<<"Hello!\n";}
: };
:
: int main()
: {
: ClassA* a;
: a->test();
: return 0;
: }
:
:
: This compiles and runs fine printing "Hello!" to stdout. I've tried this with two different g++ compilers, VS2007 and Borland C++ 5.5.1. As you can see, the pointer isn't explicitly initialized.
:
: The 2nd case is when a pointer to object is introduced as a member of a class. To get the picture, please consider the following code.
:
:
: #include <iostream>
: class ClassA
: {
:
: public:
: ClassA(){}
: virtual ~ClassA(){}
: ClassA* a;
: void test(){std::cout<<"Hello!\n";}
: };
:
: int main()
: {
: ClassA* a;
: a->a->test();
: return 0;
: }
:
:
: This compiles and runs fine too. This is an interesting case, because ClassA contains a pointer to an object of type ClassA, which of course then contains a pointer to an object of type ClassA etc.
:
: On gnu compilers this 'recursion' seems to be limited to two layers, i.e.
:
:
: a->a->a->test();
:
: will segfault. However, with both VS2007 and Borland there doesn't seem to be a limit.
:
: Could someone please tell me what are the rules behind this behavior? If someone could cite me the appropriate sections of ISO/IEC 2003 C++ standard, it would be appreciated a lot.
:
: Thanks.
:
According to my knowledge, pointers aren't initialized.
Your first code could work, becouse the compiler makes youre class static, becouse it doesn't have any variables.
The second is a little more complex...
It could be that it initializes pointers to 0, and 0->a == 0, and then 0->a == 0, for infinity...
But that would make a segfault...