Copy Constructor

  • A copy constructor is called when an object is passed by value. Copy constructor itself is a function. So if we pass argument by value in a copy constructor, a call to copy constructor would be made to call copy constructor which becomes a non-terminating chain of calls. Therefore compiler doesn’t allow parameters to be pass by value.
  • private constructors and destructors are quite useful while implementing a factory where the created objects are required to be allocated on the heap. The objects would, in general, be created/deleted by a static member or friend. Example of a typical usage:
class myclass
{
public:
    static myclass* create(/* args */)  // Factory
    {
        return new myclass(/* args */);
    }

    static void destroy(myclass* ptr)
    {
        delete ptr;
    }
private:
    myclass(/* args */) { ... }         // Private CTOR and DTOR
    ~myclass() { ... }                  // 
}

int main ()
{
    myclass m;                          // error: ctor and dtor are private
    myclass* mp = new myclass (..);     // error: private ctor
    myclass* mp = myclass::create(..);  // OK
    delete mp;                          // error: private dtor
    myclass::destroy(mp);      // OK
}
  • While returning from a function, destructor is the last method to be executed. The destructor for the object “ob” is called after the value of i is copied to the return value of the function. So, before destructor could change the value of i to 10, the current value of i gets copied & hence the output is i = 3
#include <iostream>
using namespace std;
  
int i;
  
class A
{
public:
    ~A()
    {
        i=10;
    }
};
  
int foo()
{
    i=3;
    A ob;
    return i;
}
  
int main()
{
    cout << foo() << endl;
    return 0;
}
  • 23
    Shares