zach
zach

Reputation: 95

Class member initializer:syntax and usage

Say there is a class:

class person {
    int age;
    string name;

    public:
       person(int age,string name)
            :age(age),name(name)
                {}
};

I have the following questions:

Thanks!

Upvotes: 2

Views: 54

Answers (2)

Jarod42
Jarod42

Reputation: 217283

Can the constructor initializer(with the ":" syntax) be used somehow outside of classes?Is it just for classes?

Member initializer lists can only be used by constructors only.

A variable declaration such as int x(2) works for obvious reasons.x is an object with value of 2. But age(age), how does that work? Is the syntax made that way to make initialization easier?

Based on that,how come can the parameter age & member age have the same name and not confuse the compiler? Member age is in scope, but parameter age is also in scope. When this happens with ordinary functions, the "localest" is the one that prevails.

we have and expect member(init), so for member, only members of the class are seen (and Base class or own class for delegating constructor). We can say that we are only in the scope of the class.

For init, indeed regular scope applies, and parameters age/name hides members with same name.

Upvotes: 1

darune
darune

Reputation: 10972

It doesn't 'confuse' the compiler. Since it's a member initializer list it's scope is the same as constructor. Therefore function scope wins over class scope. And therefore the member age is initialized with the paramter age.


Normally I would not use the same name (even though certainly possible) as it's both brittle and somewhat unclear. For example:

struct Decision {
  bool launch_nukes;
  Decision(bool /*launch_nukes*/)  : launch_nukes(launch_nukes) {
  }
};

At best will only give a warning.

Upvotes: 1

Related Questions