Constructor in Object Oriented Programming

Q. 1 What is the ambiguity between default constructor and default argument constructor in Object Oriented programming? 
In an C++ program, the default argument constructor can be called with either one argument or with no arguments. when called with no arguments, it becomes a default constructor. When both these forms are used in a single class, then it cause ambiguity for a statement such as A a; The ambiguity is whether to call A :: A() or A :: A(int i=0) 

Q. 2 Define copy constructor in Object Oriented programming?  
In an C++ program, a copy constructor is used to declare and initialize an object from another object in a single class. It takes a reference to an object of the same class as an argument. 
For example: A obj2(obj1);  this statement would define the object obj2 at the same time and initialize it to the values of obj1. 
Another form of this statement is A obj2 = obj1; The process of initializing through a copy constructor is known as copy initialization . 


Q. 3 Define multiple constructors (constructor overloading) in Object Oriented programming?  . 
In an C++ program, when a class that has different types of constructor then that class is known as multiple constructors class. 
Let us explain the working of multiple constructor in a class with the help of an example:
Program Code: 
#include<iostream> 
using namespace std;
class A 
int a;
int b; 
public: 
A( ) //default constructor of class A
a = 0;
b = 0;
cout<<" Value of a and b after initialization through default constructor of class A :";
cout<<a<<" "<<b;
cout<<endl;
A(int x, int y) //parameterized constructor of class A
a = x; 
b = y; 
cout<<" Value of a and b after initialization through parameterized constructor of class A :";
cout<<a<<" "<<b;
cout<<endl;
};
int main() 
A obj1; //invokes default constructor of class A 
A obj2(5, 6); //invokes parameterized constructor of class A
return 0; 


The program output is tested on www.jdoodle.com
Output:
Value of a and b after initialization through default constructor of class A : 0 0
Value of a and b after initialization through parameterized constructor of class A : 5 6


Thanks
Mukesh Rajput
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

1 comments: