Home > Net >  Assigning a class variable in class definition versus at class instantiation
Assigning a class variable in class definition versus at class instantiation

Time:09-15

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.

CodePudding user response:

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.

CodePudding user response:

Is the variable assigned in the class definition accessible by all class instances?

No!

The difference is that you default-initialize the member variables and then assign values to them in the first case. In the second case you value-initialize them - which is preferred. A third option, that also value-initializes them, is to use the member-initializer list:

class Foo
{
    private:
        int x;
        double y;

    public:
        Foo() : x{0}, y{1.}
        {
        }
};
  • Related