How a designer of a class can ensure that no one outside the class can make a copy of the objects of their class?

5 Years
Discussion Span
Last Post by Moschops

If you make any function within that class pure virtual then you can't create a object of that class. If I understand you correctly or make the inheretence private like Ancient Dragon said.

Edited by Phillamon


If you means stopping someone doing something like this:

someClass pleaseDoNotCopyMe;
someClass IwantToCopy;

IwantToCopy = pleaseDoNotCopyMe; // Forbid this
someClass anotherCopy(pleaseDoNotCopyMe); // Also forbid this

you can make a private assignment operator and copy constructor

    someClass (const someClass & theOneToCopy); // no body - forbid copy construction
    someClass & operator= (const someClass & someClass); // no body - forbid assignment

If someone tries to write code that uses the copy or assignment, the code will refuse to link.

C++11 code for the same thing; in my opinion, better as it's both easier to understand the intention whilst reading, and this will cause error at compile time rather than link time:

    someClass (const someClass & theOneToCopy) = delete; 
    someClass & operator= (const someClass & someClass) = delete; 
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.