C ++ calls a static method

Say you have the following class:

struct Foo {        
    static void print(std::string x) { std::cout << x << std::endl; }       
};

What is the difference between calling printlike

Foo foo; //Or a pointer...
foo.print("Hello world");

and

Foo::print("Hello world");

?

+4
source share
3 answers

There the obvious difference is that the first version should build and destroy a Foo.

Then there is an obvious similarity in that both versions do the same thing when calling a function (they build a line, print, etc.).

A less obvious difference is the evaluation of the two expressions. You see, although it is not required for the call Foo, it is still evaluated as part of the expression:

[class.static] / 1

X X:: s; . , .

. . , Foo constexpr.

+6

. .

Foo::print("Hello world"); ; , , print static. foo.print("Hello world"); , , . , foo.

, , , , print ! , , , .

+6

. , . , :

class A{
    public:
        A(){count++;}
        ~A(){count--;}

        static int count;
};

int A::count = 0;

int main(){
    A aObj, bObj, cObj;

    std::cout << "number of A instances: " << A::count << std::endl;
    std::cout << "number of A instances: " << aObj.count << std::endl;

    return 0;
}
0

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


All Articles