Search code examples
c++staticinstantiation

class(with static member) initialization in c++


I was trying to understand friend functions and I found myself writing the following code

though I have understood the friend functions, this code leaves me with new questions:

  1. how does the class initialise here when I havn't instantiaied any object

I know static member is shared by all objects of the class and is initialized to zero when the first object is created

  1. at what point does the variables base_i and derived_i get assigned to respective values from code

I suppose it happens at return derived::derived_i + derived::base_i;

  1. if so, does that also allocate the memory for all the other members of class at that point, specifically also for newVar in this case
#include <iostream>

class base
{
private:
    static int base_i;
    float newVar;
public:
    friend int addClasses();
};

int base::base_i = 5;

class derived : private base
{
private:
    static int derived_i;
public:
    friend int addClasses();
};

int derived::derived_i = 3;

int addClasses()
{
    return derived::derived_i + derived::base_i;
}

int main()
{
    std::cout<<addClasses()<<std::endl;
}

Solution

  • how does the class initialise here when I havn't instantiaied any object

    You've initialised the variable in its definition:

    int base::base_i = 5; // <-- the initialiser
    

    The language implementation takes care of the rest.


    at what point does the variables base_i and derived_i get assigned to respective values from code

    Non-local variables with static storage duration are initialised before main is called.


    does that also allocate the memory for all the other members of class at that point, specifically also for newVar in this case

    Memory for non-static member variables is "allocated" when memory for instance of the class is allocated. You didn't instantiate the class in the example program.