C++에서 const 키워드는 "상수성(constness)"을 나타내며**, 값을 변경할 수 없음**을 의미합니다. 사용되는 위치와 맥락에 따라 다양한 형태로 활용됩니다.

1. 기본 상수 변수

const int x = 10;
// x = 20;  // 오류! const 변수는 수정 불가

const std::string name = "Alice";
// name = "Bob";  // 오류!

특징: 선언과 동시에 초기화해야 하며, 이후 값을 변경할 수 없습니다.

2. 포인터와 const

포인터에서 const는 위치에 따라 의미가 달라집니다.

int a = 10, b = 20;

// 1. 포인터가 가리키는 값이 const
const int* ptr1 = &a;
// *ptr1 = 30;  // 오류! 가리키는 값 변경 불가
ptr1 = &b;      // OK! 포인터 자체는 변경 가능

// 2. 포인터 자체가 const
int* const ptr2 = &a;
*ptr2 = 30;     // OK! 가리키는 값 변경 가능
// ptr2 = &b;   // 오류! 포인터 변경 불가

// 3. 둘 다 const
const int* const ptr3 = &a;
// *ptr3 = 30;  // 오류! 가리키는 값 변경 불가
// ptr3 = &b;   // 오류! 포인터 변경 불가

기억법: const를 기준으로 왼쪽은 가리키는 값, 오른쪽은 포인터 자체를 의미합니다.

3. 함수와 const

const 매개변수

void printValue(const int value) {
    // value = 100;  // 오류! 매개변수 수정 불가
    std::cout << value << std::endl;
}

void printArray(const int arr[], int size) {
    // arr[0] = 10;  // 오류! 배열 원소 수정 불가
    for (int i = 0; i < size; i++) {
        std::cout << arr[i] << " ";
    }
}

const 반환값

const std::string getName() {
    return "Alice";
}

// const 객체를 반환하면 수정할 수 없음
// getName() = "Bob";  // 오류!

4. 클래스와 const

const 멤버 변수

class Person {
private:
    const int id;           // const 멤버 변수
    std::string name;

public:
    // 초기화 리스트에서 반드시 초기화
    Person(int id, const std::string& name) : id(id), name(name) {}

    int getId() const { return id; }  // const 멤버 함수

    // const 멤버 변수는 수정 불가
    // void setId(int newId) { id = newId; }  // 오류!
};

const 멤버 함수

class Rectangle {
private:
    double width, height;

public:
    Rectangle(double w, double h) : width(w), height(h) {}

    // const 멤버 함수: 객체 상태를 변경하지 않음
    double getArea() const {
        return width * height;
    }

    double getWidth() const { return width; }
    double getHeight() const { return height; }

    // 비const 멤버 함수: 객체 상태를 변경할 수 있음
    void setWidth(double w) {
        width = w;
    }

    void setHeight(double h) {
        height = h;
    }
};

const 객체

const Rectangle rect(10.0, 5.0);

// const 객체는 const 멤버 함수만 호출 가능
double area = rect.getArea();    // OK
double w = rect.getWidth();      // OK

// rect.setWidth(15.0);          // 오류! 비const 함수 호출 불가