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

  • Context: C/C++ 
  • Thread starter Thread starter yungman
  • Start date Start date
  • Tags Tags
    C++
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
6 replies · 2K views
yungman
Messages
5,741
Reaction score
291
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
 
Physics 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   Reactions: DaveC426913
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