C/C++ What Does :x(a) Mean in a C++ Constructor?

  • Thread starter Thread starter yungman
  • Start date Start date
  • Tags Tags
    C++
AI Thread Summary
The discussion centers around understanding a specific line of C++ code involving constructors and initializer lists. The line in question, "Base(int a) :x(a) {}", is clarified as using an initializer list to set the member variable x to the value of the parameter a. Participants explain that the empty braces in the default constructor signify that it must have a function body, even if it contains no executable statements. The conversation also includes references to external resources for further learning about constructor initialization. Overall, the thread emphasizes the importance of understanding initializer lists in C++ programming.
yungman
Messages
5,741
Reaction score
294
I am copying some program from youtube videos. This is the program I copied:
C++:
#include <iostream>
using namespace std;
class Base
{ int x;
  public:  Base() {} Base(int a) :x(a) {  }
           int get(){return x;}
           void set(int a){x=a;}
};
int main()
{    Base b1; Base b2(10);
    b2.get();    b2.set(20);    return 0;
}

I don't know what is :x(a) in line 5 .

I really don't even understand line 5, Base() {} Base(int a) :x(a) { } what is this?

Never learn this, don't even know the name to search online. Please help

Thanks
 
Technology news on Phys.org
Have you tried Googling the line itself?
"public: Base() {} Base(int a) :x(a) { }"

I suspect that it is shorthand for some sort of empty class but my C++ is very rusty.

Code:
public: 
    Base()
    {
    
    } Base(int a) :x(a)
      {
      
      }
 
DaveC426913 said:
I suspect that it is shorthand for some sort of empty class but my C++ is very rusty.
No, it's not. That line merely initializes the x member to the value that a represents. Just as @phyzguy said.
 
  • Informative
Likes DaveC426913
The reason the empty braces are there is that a constructor has to have a function body, even if there are no executable statetments.
 
  • Like
Likes yungman
jtbell said:
The reason the empty braces are there is that a constructor has to have a function body, even if there are no executable statetments.
Just want to say thank you for your thread on ThreeVector. I really learn a lot so far and I am still working on it. I take where you start and run with it to see what should and what should not be done and why.

Thanks
 

Similar threads

Replies
25
Views
2K
Replies
22
Views
3K
Replies
13
Views
2K
Replies
36
Views
3K
Replies
23
Views
2K
Replies
40
Views
3K
Replies
39
Views
4K
Back
Top