Does a C ++ constructor call from another function member / constructor list initializers?

In a C ++ object, when you call a constructor from another constructor or member function (after the object is already constructed), does the initializer list execute the constructor you are calling?

+3
source share
4 answers

In C ++ 11, you can delegate a constructor delegate to another constructor in the same class, for example 1 :

#include <iostream>
struct SomeType  {
    int number;

    SomeType(int new_number) : number(new_number) {}
    SomeType() : SomeType(42) {}
};

int main() {
  SomeType a;
  std::cout << a.number << std::endl;
}

In this case, after this delegation it is forbidden to have a list of initializers, for example. changing the previous example to:

SomeType() : SomeType(42), number(0) {}

- error.


If the question was “Asked with an inheritance relation, a list of callers?”? the answer is yes, for example.

#include <iostream>
struct SomeBase {
  SomeBase(int) {}
};

struct SomeType : SomeBase {
    int number;

    SomeType(int new_number=0) : SomeBase(new_number), number(new_number) {}
};

int main() {
  SomeType a;
  std::cout << a.number << std::endl;
}

This is great and works exactly as you hope.


, ++ ++ 11 , - :

#include <iostream>

struct SomeType {
    int number;

    SomeType(int new_number) : number(new_number) {}
    SomeType() {
      SomeType::SomeType(0); // Error!
    }
};

int main() {
  SomeType a;
  std::cout << a.number << std::endl;
}

.

( , , ), , , , :

#include <iostream>

struct SomeType {
    int number;

    SomeType(int new_number) : number(new_number) {}
    SomeType() {
      SomeType(0); 
      number = 42;
    }
};

int main() {
  SomeType a;
  std::cout << a.number << std::endl;
}

SomeType. , . , , , , . , , , , , , , - !

1 ++ 11

+2

, WITHIN . , , BASE ( ), THEN .

- ALWAYS EVEN, ( ). , , DECLARATION , , . base . ++ , ALWAYS , , - , .

+1

.

, , Init() .

0

, , . (, ), , .

0

All Articles