Recently MeroSpark is lunched with more features and services, now you can ask your question, sell your books, share your notes and many more. Visit now and create your account to take full advantage of MeroSpark.

Constructor | Concept and Declaration – Object Oriented Programming (OOP)

Download our Android App from Google Play Store and start reading Reference Notes Offline.

constructorsConstructor | Concept and Declaration
Object Oriented Programming (OOP)
Third Semester | Second year
BSc.CSIT | Tribhuvan University (TU)

Constructor is used to create the object in object oriented programming language. Whenever an object is created, the special member function, that is constructor will be executed automatically. Constructors are used to allocate the memory for the newly created object and they can be overloaded so that different form of initialization can be accommodated. If a class has constructor, each object of that class will be initialized. It is called constructor because it constructs the value of data members of the class.

Declaration of Constructors
A member function with the same name as its class is called constructor and it is used to initialize the objects of that class type with an initial value. Objects generally need to initialize variables or assign dynamic memory during their process of creation to become operative and to avoid returning unexpected values during their execution. For example, to avoid unexpected results in the example given below we have initialized the value of rollno as 0 and marks as 0.0.

In order to avoid that, a class can include a special function called constructor, which is automatically called whenever a new object of this class is created. This constructor function must have the name as the class, and cannot have any return type; not even void. A constructor is declared and defined as follows:

//class with constructor
class student
int rollno;
float marks;
// constructor student declared having same name as that of its class
rollno = 0;
// constructor value initialized
Marks = 0.0;

In the above example class student has the constructor function defined with the same name and its values are initialized after creating it. When a class contains a constructor like one defined above, it is granted and understood that an object created by the class will be initialized automatically. The output of the above C++ program is rollno and marks of the student class.

(Visited 275 times, 1 visits today)

Posted By : Digvijay | Comment RSS | Category : Third Semester
Tag :

Post a Comment

Your email is never published nor shared. Required fields are marked *


Wordpress DMCA
Community | Toolbar | Android App | Founder/Developer : Hari Prasad Chaudhary | CSIT Portal Manager : Digvijay Chaudhary