Monday, 11 September 2017

const, static important examples must see. References ca be used as lvalue

- const object cannot call non-constant functions.
-

Some important examples on static:

1)
#include<iostream>
class Test {
    static int x[10];
    //int y;
};

int main()
{
    std::cout << sizeof(Test) << std::endl;
return 0;
}
Ans: 1, static members don't belong to the instances of class. they don't increase instances and class size even by 1 bit!


2)

#include<iostream>
class Test {
    private:
    static const int c[2] = { 1, 2 }; /// Error c should be integral type
    public:
static int fun() {
    return c;
}
};

int main()
{
    std::cout << Test::fun() << std::endl;
return 0;

}

https://stackoverflow.com/questions/9656941/why-cant-i-initialize-non-const-static-member-or-static-array-in-class

3)
#include<iostream>
class Test {
    public:
    static int x;
    public:
static int fun() {
    return x;
}
};

int Test::x = 5; // Error if comment this line:: undefined reference, as in func() x will seem to be undefined.  So, basically static variables which we want to use in static functions must be initialised somehow either in a class declaration by const static int x = 10; or outside class as per this line.

int main()
{
    std::cout << Test::fun() << std::endl;
return 0;

}

4) 

Even static private variables can also be initialized outside class without class object.:

5)
#include<iostream>
using namespace std;
int &fun()
{
    static int x = 10;
    return x;
}
int main()
{
    fun() = 30;
    cout << fun();
    return 0;
}
When a function returns by reference, it can be used as lvalue
output = 30
6)
#include<iostream>
class Test {
    const static int x = 5; // Error if changes to : static int x = 5; (A)
    public:
static int fun() {
    return x;
}
};

int main()
{
    std::cout << Test::fun() << std::endl;
return 0;
}

Errors:
(A) ISO C++ forbids in-class initialization of non-const static member 'Test::x'
     static int x = 5

No comments:

Post a Comment