The difference between declaring a static object and a pointer to a 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 lines 3 and line 4 are definitions, as I understood from some other stackoverflow posts about static members.

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

Q2. What is the 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)

+4
source share
3 answers

y - pointer ( - , ). static, nullptr, - (, First z; First* Second::y= &z;). , Second::y->fun(); , undefined . .

( , semantics , ). , - ++; , , SICP ( ++, , ).

. ++ reference, static.

, ( ) ++ 11. , , YMMV.

+6

1) , 1 2 , , 3 4 , .

2) - x y Second, . x First First. y First* - , .

3) . .

+3

Q1 class, . . . . , , . . ( ) .

It really answers Q3 . As for Q2 , I'm not sure which question exactly.

+2
source

Source: https://habr.com/ru/post/1662054/


All Articles