Constructors in Java and C++

Constructors:

  1. Member function whose name is same as class.
  2. It doesn't return any value not even null. It is called at the time of the creation of the object.
  3. It is called explicitly.
  4. It is always public.
Types of constructors:
  • Default
  • Parameter
  • Copy
   Default constructor: It doesn't take any argument it is used when we want to initialize data members of an object.

   Parameterized constructor: This type of constructor accept the parameter and the value is used to initialize data members of the object.

   Copy constructor: This type of constructor takes object reference as a parameter and use the passing reference to assign value to that object.


C++ Constructor Example:
Code:

#include<iostream>
using namespace std;
class Hello{
private:
//data members
int a,b;
public:
//Default Constructor.
Hello(){
a=0;
b=0;
}
//Paramterized Constructor.
Hello(int x,int y){
a=x;
b=y;
}
//Copy Constructor.
Hello(Hello &h){
a=h.a;
b=h.b;
}
//Add function
void add(){
int c=a+b;
cout<<"Sum is :"<<c<<endl;
}
};
int main(){
//h1 for default.
//h2 for paramterized.
//h3 for copy.
Hello h1,h2(2,4),h3(h2);
h1.add();
h2.add();
h3.add();
return 0;
}
view raw Constructor.cpp hosted with ❤ by GitHub
Output:
Sum is :0
Sum is :6
Sum is :6

Java Constructor Example:
Code:
class Constructor {
//data members
private int a,b;
//Default Constructor.
Constructor(){
a=0;
b=0;
}
//Parameterized Constructor.
Constructor(int x,int y){
a=x;
b=y;
}
//Copy Constructor.
Constructor(Constructor h){
a=h.a;
b=h.b;
}
//Add function
public void add(){
int c=a+b;
System.out.println("Sum is :"+c);
}
}
class UseConstructor{
public static void main(String args[]){
//c1 for default.
//c2 for parameterized.
//c3 for copy.
Constructor c1= new Constructor();
Constructor c2= new Constructor(2,4);
Constructor c3= new Constructor(c2);
c1.add();
c2.add();
c3.add();
}
}

Output:
Sum is :0
Sum is :6
Sum is :6

Comments

Popular posts from this blog

C++ programming toll plaza simulation program