+ 1
What is the difference between constructor and function?
....
4 ответов
+ 1
In addition and to make it more clear:
* Constructor instantiates and initiates the object.
Function works for already instantiated object.
* Constructor is implicitly invoked.
Function is explicitly invoked.
* Constructor has no return type.
Function has a return type.
* Constructor always has the same name as its class.
An ordinary function has its own name.
+ 1
constructor is a method of a class which is called when an object of this class is created.
Every class can have it's own methods (methods are "functions" in class which you define). Function is a piece of code you can write in order to make the same action 100 if times, e.g. calculating sum of 2 integers.
In constructor you would usually set default values to variables of the class
+ 1
Albert Whittaker :fan of DORAEMON
you can combine piece of code into a single unit and that unit is called a function... it is a set of code statements...
for example;
void Function1()
{
// do your stuff here
}
now whenever you need to do these stuffs , you call that function rather than writing entire stuff every time...
in above one, void is return type of function..
function can be declared in a class as well as without class.
coming to constructor, it is special type of function..
constructor cannot be without class.. it is special function defined in class... it gets automatically once you create object of class... construction cannot have return type and it's name must be same as class name..
like function, constructor can also be overloaded.. purpose of constructor is to allocate memory of class members and assign values to them..
feel free to ask for any clarification
- 1
"constructor does'nt have a return type, the name of constructor should be the same as the class name and functions can have return type and the name is user defined. constructor initiate the object and function is a method work for initiated object.