Copy Constructors |
CONCEPT
A copy constructor is a special constructor that is called whenever a new object is created and initialized with the data of another object of the same class.
SYNTAX
class class-name
{
Access Specifier:
Member-Variables
Member-Functions
public:
class-name(variable)
{
// Constructor code
}
... other Variables & Functions
}
Then In Main Function
ClassName Object1(value);
ClassName Object2=Object1;
Important Note:
(Now here In the example which is given up , One Object Member Variable Values are assigned to Another Object (object2) Member Variables, this is called copy constructor.)
EXPLANATION
Many times it makes sense to create an object and have it start out with its data being the same as that of another, previously created object. For example, if MOHSIN and NOMAN live in the same house and an address object for Mohsin has already been created, it makes sense to initialize Noman’s address object to a copy of Mohsin’s. In particular, suppose we have the following class to represent addresses:
class Address
{
private:
string street;
public:
Address()
{
street = "";
}
Address(string st)
{
setStreet(st);
}
void setStreet(string st)
{
street = st;
}
string getStreet()
{
return street;
}
};
We could then create Mohsin’s address and then initialize Noman’s address to a copy of Mohsin’s using the following code:
Address mohsin("123 Main St");
Address noman = mohsin;
Recall that a constructor must execute whenever an object is being created. When an object is created and initialized with another object of the same class, the compiler automatically calls a special constructor, called a copy constructor, to perform the initialization using the existing object’s data. This copy constructor can be specified by the programmer, as we will shortly show.
ConversionConversion EmoticonEmoticon