0

I had a question on the following C++ code. Can someone explain the constructor initialization list because I don't understand why we are saying x(a) like its a function? Also in the main, why are they using b(10) and not x?

#include <iostream>
using namespace std;

class Base{
  int x;
public:
  Base(int a):x(a) {}
};

int main() {
  Base b(10);
  return 0;
}
swindy
  • 1
  • Related: [https://stackoverflow.com/questions/7665021/c-member-initialization-list](https://stackoverflow.com/questions/7665021/c-member-initialization-list) – drescherjm Mar 20 '22 at 14:42
  • In the initializer list you use `()`; When declaring a variable you use ` ();` note that the syntax is pretty similar; in the initializer list just the type is missing, since it's determined in some other place... – fabian Mar 20 '22 at 14:42
  • 2
    Better read https://www.amazon.com/C-Programming-Language-4th/dp/0321563840 – macroland Mar 20 '22 at 14:42
  • `I don't understand why we are saying x(a) like its a function?` no x(a) is not a function but one of several different ways of initialization. With that said I think it is good that you recognize this looking like a function as this problem will come up as your code gets more complicated. – drescherjm Mar 20 '22 at 14:43
  • They are using b(10) because they decided to name the `Base` variable `b`. I would have probably written `Base base(10);` as its a bad practice to use 1 letter variable names that are not loop index values. Your variable and function names should be descriptive of the purpose of the variable or function. – drescherjm Mar 20 '22 at 14:50
  • This is explained in any **beginner level C++ book** listed [here](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Jason Mar 20 '22 at 14:51

0 Answers0