Aman Raj Aman Raj - 10 days ago 7
C++ Question

Difference between declaring static object and pointer to static object

#include <iostream>
using namespace std;
class First{
public:
void fun()
{
cout<<"base fun called\n";
}
};

class Second{
public:
static First x; //Line 1
static First *y; //Line 2
};

First Second::x; //Line 3

First* Second::y; //Line 4

int main()
{
Second::x.fun();
Second::y->fun();
return 0;
}


Line 1 and Line 2 are declarations and Line 3 and Line 4 are definitions, this I have understood from some other stackoverflow posts about static members.

Q1. Why we have to define static objects like this ? (Line 3 and line 4)

Q2. Whats difference between x and y?(Line 1 and Line 2)

Q3. Where is the memory allocated for x and y objects ?(Line 3 and Line 4)

Answer

Your y is a pointer (not an object). Since it is static, it gets initialized with nullptr, unless you explicitly define it initialized to something else (e.g. have some First z; object and define First* Second::y= &z;). So Second::y->fun(); is dereferencing a null pointer, and that is undefined behavior. You really should be very scared.

We cannot answer all your questions here (an entire book would be needed, and the notion of pointer and its semantics is difficult to explain, and related to pointer aliasing; read also about virtual address space). So take a few weeks to read some good book like Programming - Principles and Practice Using C++; you probably will benefit by also reading SICP & Introduction to Algorithms (even if neither is about C++; however both are related to programming, which is difficult to learn).

See also some good C++ reference site, it gives a short explanation about static class members.

Notice that using raw pointers is often (but not always) a bad smell in genuine C++11. You probably should consider having smart pointers, but YMMV.