Last active
June 13, 2019 19:44
-
-
Save jdee/32e59a565c1a050437a21df172cd6970 to your computer and use it in GitHub Desktop.
Const and reference members
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
using namespace std; | |
class MyThing | |
{ | |
public: | |
/* | |
* Have to override default constructor to initialize const and reference members. | |
* Note mVarValue doesn't have to be explicitly initialized. Args almost | |
* always have to be passed to initialize these members. | |
*/ | |
explicit | |
MyThing(const string& refValue) : mConstValue(0), mRefValue(refValue) {} | |
/* Default copy constructor is usually OK. | |
MyThing(const MyThing& other) : | |
mConstValue(other.mConstValue), | |
mRefValue(other.mRefValue), | |
mVarValue(other.mVarValue) {} | |
// */ | |
/* | |
* Have to override default assignment operator and ignore these members. | |
*/ | |
//* | |
MyThing& operator=(const MyThing& other) | |
{ | |
mVarValue = other.mVarValue; | |
// can't assign const/ref once initialized | |
return *this; | |
} | |
// */ | |
private: | |
const int mConstValue; | |
const string& mRefValue; | |
string mVarValue; | |
}; | |
int | |
main(int arc, char** argv) | |
{ | |
// If anything ever actually uses mRefValue, this memory has to still | |
// be around (up to the caller). | |
string name("thing"); | |
// constructor | |
MyThing thing(name); | |
// copy constructor | |
MyThing otherThing(thing); | |
// assignment operator | |
otherThing = thing; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment