How to use const references in C++

5 Answers

0 votes
#include <iostream>

int main() {
    int x = 10;

    // Create a const reference to x
    const int& ref = x;

    std::cout << "ref = " << ref << "\n";

    // ref = 20;  // ERROR: cannot modify through const reference

    x = 30;  // modifying the original variable is allowed
    std::cout << "ref now sees: " << ref << "\n";
}



/*
run:

ref = 10
ref now sees: 30

*/

 



answered 15 hours ago by avibootz
0 votes
#include <iostream>
#include <string>

// Const reference as a function parameter

// Pass by const reference → efficient + read‑only
void printName(const std::string& name) {
    std::cout << "Name: " << name << "\n";

    // name[0] = 'X';  // ERROR: cannot modify const reference
}

int main() {
    std::string s = "Mary";
    
    printName(s);
}



/*
run:

Name: Mary

*/

 



answered 15 hours ago by avibootz
0 votes
#include <iostream>

// Binding to temporaries

int main() {
    // Bind const reference to a temporary value
    const int& r = 5 + 5;  // allowed

    std::cout << "r = " << r << "\n";

    // int& r2 = 5 + 5;  // ERROR: cannot bind non‑const reference to temporary
}



/*
run:

r = 10

*/

 



answered 15 hours ago by avibootz
0 votes
#include <iostream>
#include <string>

// Const reference to a class object

class User {
public:
    std::string name;
    User(const std::string& n) : name(n) {}
};

// Read‑only access to the object
void showUser(const User& u) {
    std::cout << "User: " << u.name << "\n";

    // u.name = "Tom";  // ERROR: cannot modify through const reference
}

int main() {
    User u("Mary");
    
    showUser(u);
}



/*
run:

User: Mary

*/

 



answered 15 hours ago by avibootz
0 votes
#include <iostream>

// Returning a const reference

class Config {
private:
    int value = 42;

public:
    // Return const reference -> efficient + read‑only
    const int& getValue() const {
        return value;
    }
};

int main() {
    Config c;

    const int& v = c.getValue();
    std::cout << "Value: " << v << "\n";

    // v = 10;  // ERROR: cannot modify
}



/*
run:

Value: 42

*/

 



answered 15 hours ago by avibootz

Related questions

1 answer 173 views
173 views asked May 23, 2018 by avibootz
1 answer 289 views
289 views asked Mar 2, 2021 by avibootz
1 answer 145 views
145 views asked May 13, 2021 by avibootz
1 answer 170 views
1 answer 163 views
1 answer 146 views
...