0

So I was editing a boilerplate cpp code for a coursera assignment and came across a rather unfamiliar syntax:

pl2_ranker::pl2_ranker(float c, float lambda) : c_{c}, lambda_{lambda} {}

Where c_ and lambda_ are both private float variables declared in class pl2_ranker.

Apparently, this constructor is assigning c to c_ and lambda to lambda_, but as a non-cpp programmer, I've never encountered such a syntax before.

Could someone please let me know what this kind of syntax is called and what benefit it provides vs the regular variable assignment inside the function body?

Vahid
  • 1,829
  • 1
  • 20
  • 35
  • 2
    It's a [member initializer list](https://en.cppreference.com/w/cpp/language/initializer_list) – cigien Apr 14 '20 at 22:57
  • 1
    _and what benefit it provides vs the regular variable assignment inside the function body?_ You can initialise references and `const` member variables this way. – Paul Sanders Apr 14 '20 at 23:00
  • Also it is _initialization_, rather than _assignment_. – Eljay Apr 14 '20 at 23:07
  • 1
    This is one of the many basic concepts of C++'s classes and objects. If you're unfamiliar with it, then you should find plenty of useful information to review [in your favorite C++ textbook](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). C++ is the most complicated general purpose programming language in use today. It's not practical to expect to learn it by reading random code and asking on a web site every time you don't understand something. Instead, you should start on Chapter 1, and continue reading one chapter at a time. That's the only way to learn it. – Sam Varshavchik Apr 14 '20 at 23:28
  • @SamVarshavchik Well, I'd be a fool not to expect that coming. But I'm not trying to learn how to code cpp here. This is a course on machine learning and it involves using a utility called meta written in cpp. So, as described in the course intro, general programming knowledge is enough to go through. I just got curious about this syntax and you guys have been more than helpful. Thank you all. – Vahid Apr 14 '20 at 23:51

0 Answers0