-1

what does the : e(data) do in the following code? Why are the curly brackets { } empty in the folowing code? Also can constant members of a class be initialized in this way? Is this kind of definition specific to a constructor or it can be applied to all functions in C++?

class binaryfile
{
    private:
        const entry &e;

    public:
        binaryfile(const entry &data) : e(data){}

        ostream& write(ostream &o)
        {
            o<<e.b_write();
        }
}
  • 1
    The reason WHY you do it this way is because the member variable is const, so you can call it's constructor but you can't assign anything to it. So you can't use `binaryfile(const entry &data) : { e = data; }` but you can call the entry constructor: `binaryfile(const entry &data) : e(data){}` You can always call the constructor of a const object in order to create it - you just can't assign anything to it later. – Jerry Jeremiah May 26 '20 at 22:22
  • 1
    Sigh. The ratio of the Member Initializer List's importance to the language vs frequency of it being taught is almost infinity. – user4581301 May 26 '20 at 22:33
  • @JerryJeremiah I understand now. Thank you so much! – Pratap Biswakarma May 26 '20 at 22:37
  • @user4581301 True! I've never seen that notation in the C++ books that i read. A LOT is skipped when C++ is being taught in these books or when they are teaching it in schools! – Pratap Biswakarma May 26 '20 at 22:39
  • 1
    [Here is some good documentation](https://en.cppreference.com/w/cpp/language/constructor) on how to use the initializer list and the kinds of booby traps to look out for. Pay special attention to the initialization order as this can cause some really interesting problems. – user4581301 May 26 '20 at 22:47
  • @user4581301 This is so helpful. I appreciate it a lot! – Pratap Biswakarma May 26 '20 at 23:06

1 Answers1

1
binaryfile(const entry &data) : e(data){}

Defines a constructor which takes one argument and initializes the member variable e to that argument's value. The braces are empty because the constructor does nothing more.

It's called a member initializer list and it only works in constructor(s).

ruohola
  • 21,987
  • 6
  • 62
  • 97