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 ?
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; };
};
+ 2
A constructor is code that will be run when an object is declared.