Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between declaring static object and pointer to static object [closed]

    #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)

like image 662
Aman Raj Avatar asked Dec 10 '22 14:12

Aman Raj


2 Answers

Your y is a pointer (not an object - a pointer is not the same as the object it could point to). 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.

like image 192
Basile Starynkevitch Avatar answered Feb 15 '23 22:02

Basile Starynkevitch


1) Because when the objects of a class are created, there will be no memory allocated for theirs static members - so lines 1&2 declare that there should be such members, but lines 3&4 define where the memory should be allocated.

2) There is literally no big difference - both x and y are just members of class Second, but of different type. x is of type First and its size equals to sum of First members. y is of type First* - its size depends on a size of pointer used in a particular compilator.

3) There is already a good answer about memory allocation for static members. The most common implementation is to use data segment of a program.

like image 39
Artalus Avatar answered Feb 15 '23 22:02

Artalus