简体   繁体   中英

What will happen if constructor is not used in class in c++

I am not enable to understand why constructor is used, it's functioning can be done through different method also by using "function". What constructor is able achieve in programming language that we can't achieve through function in c++. Instead if constructor we can use function also.

Main difference between constructor and function. What is the purpose of using constructor in c++

Constructor has one goal: to establish the class invariant. class is usually not just a bunch of member fields and functions: there's usually a relationship between those members that must be established and then held in order for the program to function correctly. Eg a Rational class that consists of int n and size_t d and represents n/d should make sure that d != 0 and it can't be simplified anymore. Some class members might also be const , in which case the last point you can set the value of them (by initialization) is in the constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM