C++ - SPLessons

C++ Copy Constructors

Home > Lesson > Chapter 41
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

C++ Copy Constructors

C++ Copy Constructors

shape Description

Consider an object is created. The created object is initialized by using another object of same class. The object used for initializing the first object generates a constructor called as "copy constructor".
Copy constructors are used when pointer variables are declared in a class to maintain a copy to the original object of the same type.

shape Syntax

class_name (const class_name &obj) { //constructor body }

shape Example

[c] #include <iostream> using namespace std; class Triangle { public: int getBase( void ); Triangle( int bas ); //constructor Triangle( const Triangle &obj); // copy constructor ~Triangle(); // destructor private: int *ptr; }; Triangle::Triangle(int bas) { cout << "simple constructor allocating ptr" << endl; // allocate memory for the pointer; ptr = new int; *ptr = bas; }[/c] Output [c] simple constructor allocating ptr Copy constructor allocating pointer. The base of Triangle: 20 memory is cleaned up! memory is cleaned up![/c]

C ++ - Related Information
C++ Loops
C++ if
Storage Classes in C++
Type Casting in C++
C++ Input/Output


Click Here to Join - Telegram Channel