This means, now the code tries to get the value before setting it. Well, to answer this question, lets assume that in the same program (shown above), the call to setNumOfCities() and getNumOfCities() is interchanged. Now one would ask what’s the actual role of these functions? In which scenarios are they really required? One option would be to set internal state to some empty default value, but that means that either it is not a needed asset for the object but rather optional, or we are entering a bad state, which is not a thing we should want to deal with. So this confirms that these special functions are called internally or automatically (from a developer’s point of view). We usually will notice that in the object’s constructor. Observe that as the object of the class was created, constructor of the class was executed and just when the object was about get destroyed, the destructor was called. So we see that we used g compiler for compiling the c code and in our case, the code compiled without any warning or error. Here is how a C code is compiled on Linux : $ g -Wall cnstrDestr.cpp -o cnstrDestr Let’s verify the above given explanation by executing the code shown above. Similarly, a destructor is a special function that gets called automatically when a class object is deleted or goes out of scope. In precise terms, a constructor is a special function that gets called automatically when the object of a class is created. The function that have a ‘~’ before the name is destructor while the other one is constructor.Īs we have already discussed that a constructor is used for creating an object.Observe that there are two functions with same name as that of class ie country.Std::cout<<"\n Number of cities is equal to "<<num Let’s understand the concept of constructors and destructors through this example : #include If you are new to C , you should first understand the concept of C classes. In this article, we will study the concept of constructors and destructors through working examples. Both constructor and destructor are more or less like normal functions (but with some differences) that are provided to enhance the capabilities of a class.Ĭonstructor, as the name suggests is used to allocate memory (if required) and construct the objects of a class while destructor is used to do the required clean-up when a class object is destroyed. Constructors and destructors are fundamental to the concept of classes in C .
0 Comments
Leave a Reply. |