#include using namespace std; struct BigStruct{ int arr[100]; double d; }; void funcByValue(int arg) { arg = 1; } void funcByRefCStyle(int *arg) { *arg = 1; // inconvenient to always use '*'! } void funcByRefCppStyle(int &arg) { arg = 1; } // Will copy struct variable, expensive void funcByValStruct(struct BigStruct arg) { arg.d = 3.14; } // Only gets pointer struct variable, cheap. Modification reflected in caller // function. Cumbersome to use "->" instead of ".". void funcByRefCStyleStruct(struct BigStruct *arg) { arg->d = 3.14; // OK, changes called copy } // Only gets pointer struct variable, cheap. Modification reflected in caller // function. void funcByRefStruct(struct BigStruct &arg) { arg.d = 3.14; // OK, changes called copy } // Cannot modufy structure void funcByRefStructConst(struct BigStruct const &arg) { // arg.d = 3.14; // Not allowed } int main() { int intVar1, intVar2; // constant declaration. Cannot be changed later. const int constantVar = 268; //constantVar = 168; // not allowed // pointer pointing to constant data const int *constData; // equivalent to "int const *constData;" constData = &intVar1; // OK constData = &intVar2; // OK //*constData = 10; // Not allowed. // constant pointer, cannot be reassigned int * const constPtr = &intVar1; *constPtr = 10; // OK // constPtr = &intVar2; // Not allowed // constant pointer pointing to constant data int const * const constPtrData = &intVar1; //*constPtrData = 10; // Not allowed //constPtrData = &intVar1; // Not allowed // Pass argument by Value intVar1 = 268; funcByValue(intVar1); cout << "intVar1 after funcByValue: " << intVar1 << endl; // C-Style Pass by reference intVar1 = 268; funcByRefCStyle(&intVar1); cout << "intVar1 after funcByRefCStyle: " << intVar1 << endl; // C++ Style Pass by reference intVar1 = 268; funcByRefCppStyle(intVar1); cout << "intVar1 after funcByRefCppStyle: " << intVar1 << endl; // Passing by reference is useful for two tasks: // 1. To modify variable value in callee function, and // 2. To reduce the overhead of passing a large class/struct by value // "const" keyword used if we want 2 without 1. struct BigStruct structVar; structVar.d = 268; funcByValStruct(structVar); cout << "After funcByValStruct: structVar.d = " << structVar.d << endl; structVar.d = 268; funcByRefCStyleStruct(&structVar); cout << "After funcByRefCStyleStruct: structVar.d = " << structVar.d << endl; structVar.d = 268; funcByRefStruct(structVar); cout << "After funcByRefStruct: structVar.d = " << structVar.d << endl; structVar.d = 268; funcByRefStructConst(structVar); cout << "After funcByRefStructConst: structVar.d = " << structVar.d << endl; // Another use of "const": // To indicate that class member function cannot modify "non-mutable" class // data members class Example{ private: int var; mutable int mutVar; public: void setVal(){ var = 10; // OK mutVar = 100; // OK } void setValConst() const{ // var = 10; // Not allowed mutVar = 100; // OK } }; return 0; }