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.

Application of Constructors – Object Oriented Programming (OOP)

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

Application of ConstructorsApplication of Constructors
Object Oriented Programming (OOP)
Third Semester | Second year
BSc.CSIT | Tribhuvan University (TU)

Application of Constructors
A constructor is a special function that is created when the object is created or defined. This particular function holds the same name as that of the object and it initializes the instance of the object whenever that object is created. The constructor also usually holds the initialization of the different declared member variables of its object. Unlike some of the other functions, the constructor does not return a value, not even void.

When you create an object, if you do not declare a constructor, the compiler would create one for your program; this is useful because it lets all other objects and functions of the program know that this object exists. This compiler created constructor is called the default constructor. If you want to declare your own constructor, simply add a function with same name as the object in the public section of the object. When you declare an instance of an object, whether you use that object or not, a constructor for the object is created and signals itself.

A class can have multiple constructors for various situations. Constructors overloading are used to increase the flexibility of a class by having more number of constructor for a single class. To illustrate this let us take the following C++ program
class Computer
int x;
Computer() { x=y=0;}
Computer(int a) {x=y=a;}
Computer(int a, int b) {x=a;y=b;}
int main()
Computer A;
Computer A1(4);
Computer A2(8, 12);
cout<<”computer A’s x,y value:”<<A.x<<”,”<<A.y<<”\n”;
cout<<”computer A1’s value:”<<A1.x<<”,”<<A1.y<<”\n”;
cout<<”computer A2’s value:”<<A2.x<<”,”<<A2.y<<”\n”;
return 0;

Here in the above example, the constructor “computer” is overloaded thrice with different initialized values.

(Visited 886 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