Search code examples
c++initializationdefault-constructorconstructdatamember

Assigning a class variable in class definition versus at class instantiation


What are the ramifications of assigning a class variable when defining the class versus in the class constructor? Is the variable assigned in the class definition accessible by all class instances?

Example of assignment at instantiation:

class Foo
{
    private:
        int x;
        double y;

    public:
        Foo()
        {
            x = 0;
            y = 1.;
        }
};

Example of assignment in class definition:

class Foo
{
    private:
        int x = 0;
        double y = 1.;

    public:
        Foo();
};

edit: As to the class member being accessible by all instances, I think I was looking for the notion of a static declaration, I guess I'm just new to the curly brace languages.


Solution

  • In this code snippet

    int x = 0;
    double y = 1.;
    

    there is no assignments. There are initializations.

    In this code snippet

    Foo()
    {
        x = 0;
        y = 1.;
    }
    

    there is indeed used the assignment operator.

    In general for objects of complex types it can be 1) impossible (either the default constructor or the assignment operator is not available) or 2) requiring many resources because at first default constructors are called that create the objects and after that there are called assignment operators.

    It is desirable to define constructors at least like for example

        Foo() : x( 0 ), y( 1 )
        {
        }
    

    using mem-initializer lists.