Working with pointers in C requires a lot of practice to avoid memory leaks and dangling pointers. We discussed them in length in the previous post, Pointer Hazards in C . In object oriented paradigm, whenever you declare an object of user defined class type, a special function known as constructor is automatically invoked. Similarly when you want to copy an object to another object, copy constructor gets invoked. Writing an efficient and error free constructor is essential to the construction of a good program. In this post I shall explain how to write a good and efficient constructor and a copy constructor, paying special attention to pointer hazards.
Posts Tagged ‘oop’
After talking about constructors and destructors, next up in my series on object oriented programming is how to use setters. Setters are functions that are used to change the values of data members inside classes. They are very important, as they are the only route through which we can change the value of our data members after an object is instantiated.
Just like function templates, we can also make and use class templates in our program. With the help of class templates, a whole class could be made generic. Each function declared within the class is a template function by default. Class templates behave much like the function templates though there is a lot more to be associated and understood with them. Class templates can also be specialized like specializing function templates. For this article, I would explain only how to make a simple class, a template class.
Now that we”ve had a look at the types and uses of constructors, let us move on to the concept and use of destructors in C . Destructors are important in object oriented programming, as they are called whenever the life of an object ends. To understand destructors, first we must know that when dealing with classes, we often encounter a situation where pointers are used. A class with a pointer/pointers as data members are usualy allocated memory in a constructor. As a simple example, let us use a class called “point”, with a redundant data member called int * ptr.