Copy Constructor in C++
Copy Constructor in C++
Copy constructor is a special type of constructor used to create the copy of an object of the class. This constructor accepts an object of the same class as arguments and copies it to another object of the class being created.
Synatx
class ClassName
{
Access_specifier:
…
…
ClassName(ClassName &object)
{
dataMember1=object.dataMember1;
dataMember2=object.dataMember2;
…
…
}
…
…
};
Example
In above example, Person class is defined having a copy constructor defined at line 19. It accepts object of the same class as an argument and copy the values of its data members to the newly created object (lines 21 and 22). Copy constructor is called as explained in the following example.
In above code, an object of class Person is created at line 32 at its copy is created at line 34 by calling the copy constructor of the class Person. The output of the above code is as below showing that both the objects (p1 and p2) have the same values.
More Related Articles For You
- What is C++
- C++ and Object Oriented Programming OOPS concepts
- Syntax and Structure of C++ program
- Data Types in C++
- C++ Variables
- Types of operators in C++
- Decision making in C++
- C++ Loop Types
- Storage Classes in C++
- Functions in C++
- Classes and Objects in C++
- Access controls in C++ Classes
- Defining Class and Object in C++
- Accessing Public and Private Data Members in C++
- Member Functions in Classes
- Types of Member Functions in C++
- Inline Functions in C++
- Namespaces in C++
- Function Overloading in Classes in C++
- Constructors and Destructors in C++
- Static Keywords in C++
- Const Keyword in C++ Programming
- References in C++
- Pointer to Members in C++ Classes
- Introduction to Inheritance
- Types of Inheritance
- Order of Constructor Call in Inheritance
- Upcasting in C++
- Function Overriding in C++
- Virtual Functions in C++
- Abstract Class and Pure Virtual Functions in C++
- Virtual Destructors in C++
- Operator Overloading in C++
C++ Tutorial
C++ Quizzes