C ++ constructor definition

All the constructor methods here do the same. I mainly use method2, but I first saw method3. Have you seen Method1 in some places, but don’t know exactly what the differences are between them? Which one is the best way to define constructors and why? Are there any performance issues?

  1 class Test
  2 {
  3     private:
  4         int a;
  5         char *b;
  6     public:
  7         Test(){};
  8         
  9         // method 1
 10         Test(int &vara, char *& varb) : a(vara), b(varb){}
 11         
 12         // method 2
 13         Test(int &vara, char *& varb)
 14         {
 15             a = vara;
 16             b = varb;
 17         }   
 18         
 19         //method 3
 20         Test(int &vara, char *& varb)
 21         {
 22             this->a = vara;
 23             this->b = varb;
 24         }   
 25         
 26         ~Test(){}
 27 }; 

Here I used simple int and char * fields, what happens if I have many fields or complex types like struct ??

thanks

+3
source share
7 answers

For the types you use, there will probably be no difference in performance. However, for data other than POD (classes with constructors), the form:

Test(int &vara, char *& varb) : a(vara), b(varb){}

. , , POD, , . , , , .

+14

, , 1 a b, . 2 a b, THEN . , int char *.

3 - , 2.

+4

2 3. - ( ) - x this->x. , , x . :

int Foo::memberFunc() {
  return x; // Returns member variable x. Same as return this->x.
}

int Foo::memberFunc(int x) {
  return x; // Returns the argument x. Need to say return this->x to return member x
}

1 -, , .

2 3, . , - - - , , 1 .

1 , - - , 2 3, , int he constructor code, 1 , .

+3

, " ", . , .

, . , .

- , , . this-> , , .


, . , -, .

+2

3 , -

Test (int &a, char &b) 
{
    this->a = a;
    this->b = b;
}

, a b, , 2.

+1

( ) - ++. , , . , - . , . , 3 .

+1

.

1 .

2 3 ( -POD- ), .

, 2 3 , , . , POD.

, ( 1). . , .

+1

Source: https://habr.com/ru/post/1715099/


All Articles