Quartekoen
0
Q:

what is constructor

A constructor is a special method used to initialize objects in java.
we use constructors to initialize all variables in the class 
when an object is created. As and when an object
is created it is initialized automatically with the help of 
constructor in java.
  
We have two types of constructors:
Default Constructor
Parameterized Constructor

public classname(){
}
public classname(parameters list){
}
7
A constructor is a member function of a class which initializes objects of a class.
In C++, Constructor is automatically called when object(instance of class) create.
It is special member function of the class

Example:
// Cpp program to illustrate the
// concept of Constructors
#include <iostream>
using namespace std;
 
class construct 
{
public:
    int a, b;
 
    // Default Constructor
    construct()
    {
        a = 10;
        b = 20;
    }
};
 
int main()
{
    // Default constructor called automatically
    // when the object is created
    construct c;
    cout << "a: " << c.a << endl
         << "b: " << c.b;
    return 1;
}
0
Line::Line( double len): length(len) {
   cout << "Object is being created, length = " << len << endl;
}
0
Constructors are the special methods without any return type. 
Constructors have the same name with the className
Constructors are special methods, which are called 
whenever the new keyword is used to create an object of a class
By default every class always has a default constructor 
with no parameters. This default constructor is no longer there if a 
constructor is created manually
Constructors usually act to initialize instance variables or perform 
actions that need to be taken whenever an object of a class is created.
Like methods, constructors can also be overloaded. 
The same rules apply. This is done by providing a constructor with 
with a different parameters
this() can be used to call the overloaded
constructors with other parameters
0

Tags

New to Communities?

Join the community