Aman Raj Aman Raj - 1 year ago 67
C++ Question

Difference between declaring static object and pointer to static object

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

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

First Second::x; //Line 3

First* Second::y; //Line 4

int main()
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download