About assigning the values(private class)


Hey, I am a Program goer and I just started to learn c++ last week. In the tutorial I'm reading, I find an example here:

So the line 10
The snippet【Test(): count(5){}】got me mad. I know it's used for assigning value 5 to the integer count. But could anyone tell me what what every【Test()】/【count(5){}】part of this is?

Thanks in advance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
using namespace std;

class Test
{
   private:
      int count;

   public:
       Test(): count(5){}

       void operator ++() 
       { 
          count = count+1; 
       }
       void Display() { cout<<"Count: "<<count; }
};

int main()
{
    Test t;
    // this calls "function void operator ++()" function
    ++t;    
    t.Display();
    return 0;
}
Last edited on



Basically
1
2
3
4
5
6
7
8
9
10
11
12
13
Testa 

:b 
counter(5)c

{}d

/*
a: defined as special function called a constructor, which can be used to initialize the object 
b: this signifies that you are going to initialize some of the member variables 
c: this is just specifying how to init the member variable "counter", kinda like counter = 5.
d: this is the function body of the constructor function.
*/
Last edited on
@highwayman


The "constructor" here is the hint. After googled it. I think I understand the part a b and d.
Thanks man

But the part c count() right here, is it also a function? (I mean it resembles a function) If yes, why it's not declared before this line(L10)?

I hope my reply finds you directly. Since I didn't find the RPL button. So hopefully @ would help.
Last edited on
No it is not a function. If it’s any help, you can write it like count{5} too if you want, it means the same thing. It basically boils down to

1
2
3
4
// same exact functionality
Test () {
  count = 5;
}


The thing is all it is is special syntax for initialization of a variable in c++. You could do stuff like


These all do the same exact thing.
1
2
3
4
int x(5);
int xx = 5;
int xxx{5};
int xxxx={5};


I’m... not sure how else to say it. Lol.
Got it with thanks!
Yw!
@Furry Guy

Pretty mint tutorial, thanks^^
Since the original question was about class member initialization, specifically constructor initialization lists:
https://www.learncpp.com/cpp-tutorial/8-5a-constructor-member-initializer-lists/
Topic archived. No new replies allowed.