I was reading some C++ code from a basic CPU emulator and I just can't understand this:
class CPU {
private:
CPU (const CPU&){}
};
I understand pointers, I also checked this: Ampersand & with const in constructor. Apparently it is a (hard) copy constructor, but I don't understand, how does this work? why const? Why the ampersand in the end without a var name? Why private? I haven't found an example like this in my books or cplusplus.com.
On a side note:
int foo(int var) { cout << var; }
int bar(int &var) { cout << var; }
foo and bar print the same thing? bar is essentially printing *&var?
Any help is appreciated!
The &
indicates pass by reference when used in argument definitions. This converts the argument into a pointer and de-references that pointer when you use it within the function scope. In your second question both functions print the same thing because the &
simply says pass the original object by reference instead of copying it into the function header. The same content exists, the only difference is one of the functions copies the full input and the other could edit the source variable if it wanted to.
CPU (const CPU&){}
is saying the constructor requires a constant reference to a CPU object. This means you can only access const functions of CPU (and guarentee you won't change the original CPU object argument). Not having a name after the CPU&
just means you're not assigning the variable to a name within the current scope (aka the brackets after the definition will ignore the argument).
When a constructor is private it usually means there's another function which will generate the Object for you. Factories will oftentimes hide an objects constructor and require some other attributes/registration before building the object for you.