Hello everyone and welcome back to NewAgeInformers!!! In previous post we had learned that what is constructors and it's types. Again in this post we will learn another part of it. So lets get started!!!!
Constructor:-
When
we create a new variable from an object it is called as copy
constructor. There are two types of constructors.
1)
Implicit constructor. 2) Explicit constructor.
In
previous post we learned that compiler creates a copy constructor for
every class when no copy constructor is defined. This type of
constructor is known as implicit constructor. It is a special type of
constructor that a new object is created as a copy of existing
object.
Syntax
of copy constructor:
Class
name(Class name &object)
{
/*
Constructors body*/
}
While
applying the copy constructor we need to use following syntax:
Classname
new_object_name(old_object_name);
let's
take an example for better understanding.
#include<iostream.h>
classNAI
{
int
a;
public:
NAI();
/* default constructor*/
NAI(int
b)) /*parameterized constructor */
{
a=b;
}
NAI(NAI
&obj) /*copy constructor*/
{
a=obj.a;
}
void
show()
{
cout<<a;
}
};
void
main()
{
int
b;
cout<<”enter
numbers”<<endl;
cin>>b;
NAI
old(b); /* for calling copy constructor */
paNAI
new(old);
cout<<”the
original value:”;
old.show();
cout<<”\n
new value is: ”;
new.show();
cout<<endl;
getch();
}
In this program there are two
main constructors. First is default, second is parameter constructor
which we learned in previous post. Note that copy constructor, is
always declared as a passing reference parameter. We can not pass the
parameter by value.
So this is it. We will look at destructors in upcoming post. Till that bye bye!!!!!
For more interesting things keep following us :
facebook: CLICK HERE!!!!!!!!!!
Twitter: @NewAgeInformers
Instagram: @new_age_informers_
For more interesting things keep following us :
facebook: CLICK HERE!!!!!!!!!!
Twitter: @NewAgeInformers
Instagram: @new_age_informers_
Comments
Post a Comment