Constructors in Java and C++
Constructors:
Java Constructor Example:
Code:
Output:
- Member function whose name is same as class.
- It doesn't return any value not even null. It is called at the time of the creation of the object.
- It is called explicitly.
- 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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Output:
Sum is :0
Sum is :6
Sum is :6
Java Constructor Example:
Code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Post a Comment
Feel free to leave a comment...