Why do we need constructors in C++

Prior to C++ programming or Object oriented programming; procedural languages such as C language were used. Procedural language program have typical structure where variables needs to be declared to hold data and functions need to be declared to operate on these variables. To share variables among various parts of program (or with number of functions) either one needs to pass variables as parameters or should declare variable as global.

In every programming scenario any variable before using it must be initialized to some values. Reason is anything declared but not initialize may contain garbage or junk values. Performing operations on such values may bring your program down.

So original code author may write some function to initialize these variables or he will initialize at the places where “He” is using them before actually performing some operation. Think about the programmers other than original code author, there are pretty good chances that he will use them without initialising or if there is any function to initialize them, might skip to call it. This will run your program into generating incorrect output, abnormal behaviour or in the worst case program crash.

So there must be a way to initialize the variables always. Or some initialization function must be called while creating variables. C++ programming language provides a concept called constructors. Constructors guarantee that they will be called as soon as an object of class is created to initialize its member variables. They are named as constructors because they are getting called when an object is constructed.

I will describe more on constructor in subsequent blog posts.

 

Tagged with  
,

5 thoughts on “Why do we need constructors in C++

  1. Thanks for visiting our web site.

  2. pitambar hatwar says:

    thanks

  3. Hello There. I discovered your weblog the use of msn. That is a really neatly written article. I’ll make sure to bookmark it and return to read more of your helpful info. Thanks for the post. I will definitely comeback.

  4. the information you have provided is short and sweet but sir can you give me any example so dat i can understand the term Construtor

    • Every program needs data ( variables). In the days of C, it was very common to forget using variables without initializing. Good practice was to have some function that will initialize all the declared variables or data.
      With C++ compiler provide default function without return values and has same name to that of class name called as constructor. This function/constructor is meant for initializing member data/variables.

Leave a Reply