Skip to main content

Disallow the use of compiler generated functions

/* C++ 11 Update: Delete keyword */
class dog {
   public:
   dog(const dog& ) = delete; // Prevent copy constructor from being used.
                              // Useful when dog holds unsharable resource.
}



/* For C++ 03:


Solution:
 Declare them as private functions, but not define them.
 -- Members and friends get link-time error, others get compile-time error.
*/
class dog {
   private:
   dog& operator=(const dog& rhs);   
};


// Note: the same techniques can used to disallow any function from being used.





Question: Can we disallow destructor from being used? 


/* Solution */
class dog {
  public:
     void destroyMe() { delete this; }
     void dog(string message) { cout<
  private:
     ~dog() { cout<< m_name.m_str << " is destroyed.\n" << endl; }
};

int main ()
{
  dog dog1("Dog Barks");
  dog1->destroyMe();  
}  

// Error : Though we have invoke function to delete object through delete, but still when function goes out of scope destructor gets called and results in runtime error.



Solution: Create pointer on heap


int main ()
{
  dog* dog1 = new dog("Dog Barks");
  dog1->destroyMe();
}

Comments