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.
- , . ++, . , , , . , , , - . , . .
, , . , , , . , - , , , .
++ (- , C).
++ () () . .
C (int, char) - .
, - C (int, char ..) . undefined. - ++ () . , , , .
- . .
, , . , - . , .
, " ". , - , 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.
, , , , ( ) .
, ? , ?
, . - , , , , . , ( , ).
, , , . , , , :
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.
Source: https://habr.com/ru/post/1790402/More articles:UIViewController adding subview gives me error: unrecognized selector - iosгде JSR-97 (JavaHelp) - javacalling wcf 4.0 service from jquery ($. ajax) - jqueryproject compilation errors with boost asio - c ++Повторное использование класса XmlTextWriter - c#C ++ random number generation - c ++https://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1790404/ruby-nanoc-how-do-i-get-a-list-of-items-to-display-in-a-page&usg=ALkJrhhrzTL03S8bK-4oZKRhCl1hVtsbjAHow to change tomcat default deployment directory in Eclipse? - javaReplace normal field around volatile field - javaSingle view template for multiple query formats - ruby-on-railsAll Articles