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

Recommended Answers

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

private:
    someClass (const someClass & theOneToCopy); // no …
Jump to Post

All 3 Replies

Do you mean inherentence or do you mean another programmer? For inherentence just make the objects private.

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.

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

private:
    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:

private:
    someClass (const someClass & theOneToCopy) = delete; 
    someClass & operator= (const someClass & someClass) = delete; 
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.