A class declaration can contain static object of self type, it can also have pointer to self type, but it cannot have a non-static object of self type.
For example, following program works fine.
#include<iostream>
using namespace std;
class Test {
static Test self;
};
int main()
{
Test t;
getchar ();
return 0;
}
|
And following program also works fine.
#include<iostream>
using namespace std;
class Test {
Test * self;
};
int main()
{
Test t;
getchar ();
return 0;
}
|
But following program generates compilation error “field `self’ has incomplete type”
#include<iostream>
using namespace std;
class Test {
Test self;
};
int main()
{
Test t;
getchar ();
return 0;
}
|
If a non-static object is member then declaration of class is incomplete and compiler has no way to find out size of the objects of the class.
Static variables do not contribute to the size of objects. So no problem in calculating size with static variables of self type.
For a compiler, all pointers have a fixed size irrespective of the data type they are pointing to, so no problem with this also.
Thanks to Manish Jain and Venki for their contribution to this post. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!