liv2hak
liv2hak

Reputation: 14990

C++ struct constructor with member initializer list

I came across a C++ struct definition with a constructor.

struct Foo                                                                                                                                                                                                                                   
{
    int x;

    Foo( int _x ) : x(_x)
    {   

    }   
    ~Foo()
    {   
        std::cout << "Destructing a Foo with x=" << x << "\n";
    }   
};

I know about member initializer but don't quite get what _x means here? Can someone please enlighten me?

Upvotes: 0

Views: 1319

Answers (3)

kfsone
kfsone

Reputation: 24249

Foo( int _x ) : x(_x)
{   

}

This is a constructor that takes an integer which is then used to initialize the value of member variable x.

Foo f(5);
// -> f.x = 5

The reason for the underscore is to disambiguate between the function parameter and the variable it's being assigned to.

YMMV: Many development teams use similar strategies:

. Prefix all member variables with "m_", . Prefix or suffix member variables with "_", e.g. _x, x_,

It's not very common but you'll find some development teams who always disambiguate function parameters with a prefix:

class Foo {
    int m_x; // member x
public:
    Foo(int _x) : m_x(_x) {}
    int x() const { return m_x; }
};

the advantage of this approach: you can have lowercase member function names which won't conflict with parameters, so you can have getters that aren't prefixed with 'get'.

Upvotes: 0

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

That's not kind of special or magic syntax. The prefixed _ is used to distinguish the constructor parameter from the member variable symbol. That's all.

Using a definition like

struct Foo {
    int x;
    Foo( int x ) : x(x) {}
};

would just be ambiguous scope wise.

Upvotes: 2

Sam Varshavchik
Sam Varshavchik

Reputation: 118340

It means a variable named "_x". The underscore can be used in names of variables like letters, although identifiers whose names start with underscores have a long standing convention as being reserved for the compiler's library.

int _x;

Means the same thing that

int x;

means. Or "int a;", "int b;", or int anything. Variable names in C and C++ may start with underscores or letters, and consist of underscores, letters, and digits. Although, as I said, leading underscores should be avoided, as they're generally reserved for use by the compiler's library.

Upvotes: 2

Related Questions