What are the benefits of C ++ constructors?

Constructors initialize class data elements when creating an object.

My question is, what is the advantage of this initialization process? Why don't we let each object determine its initial value without calling the constructor?

And also, what is the advantage of the default constructor? In the end, he does nothing, right?

Thank.

+3
source share
5 answers

- , . ++, . , , , . , , , - . , . .

, , . , , , . , - , , , .

+17

++ (- , C).

++ () () . .

C (int, char) - .

, - C (int, char ..) . undefined. - ++ () . , , , .

- . .

+3

, , . , - . , .

+1

, " ". , - , 0. , , .

++ , ( ), , :

class Demo {
private:
    int& refInt;
public:
    //Demo() {} // illegal - will not compile since it does not intiailise refInt
    Demo(int anInt) : refInt(anInt) {} // valid, correctly initialised refInt
};

int main() {
    int a;
    Demo demo(a);

    return 0;
}

: , refInt.

, , , , ( ) .

+1

, ? , ?

, . - , , , , . , ( , ).

, , , . , , , :

  • .
  • It initializes the vtable pointer for polymorphic classes.
  • It calls the default constructors for fields other than POD.

And only when the class does not have a base class, it is not polymorphic and has only POD fields, the constructor generated by the compiler literally does nothing. But this is still important, because the base classes need to call something.

+1
source

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


All Articles