What is a constructor and how we have to declare and its working ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

What is a constructor and how we have to declare and its working ?

30th May 2019, 4:29 PM
Kandukuri Abhinav Reddy
Kandukuri Abhinav Reddy - avatar
2 Answers
+ 5
Hey. I would not entirely agree with Ben since the constructor is called when the object is being created during run-time. Meaning that the code in the constructor is called when you instantiate the class to an object, create a variable of that type so to say. Declaration and definition of the constructor depends heavily on your choice of programming language. C++ uses the following way: class Example { public: int total; Example (int initial_value) : total(initial_value) { }; void accumulate (int x) { total += x; }; };
30th May 2019, 6:05 PM
ChrA
ChrA - avatar
+ 2
A constructor is code that will be run when an object is declared.
30th May 2019, 4:31 PM
Ben Allen (Njinx)
Ben Allen (Njinx) - avatar