Menu
Coddy logo textTech

Const Member Functions

Part of the Object Oriented Programming section of Coddy's C++ journey — lesson 29 of 104.

You've seen the const keyword on getter methods in the previous lesson. But what exactly does it mean when const appears after a function's parameter list? A const member function promises not to modify any member variables of the object.

class Rectangle {
    int width;
    int height;
public:
    Rectangle(int w, int h) : width(w), height(h) {}
    
    int getArea() const {      // const member function
        return width * height;  // Reading members is allowed
    }
    
    void setWidth(int w) {     // Non-const - modifies the object
        width = w;
    }
};

The const after the parameter list tells the compiler: "This function will not change the object's state." If you try to modify a member variable inside a const function, the compiler will produce an error.

This becomes essential when working with const objects or const references. A const object can only call const member functions:

void printArea(const Rectangle& rect) {
    std::cout << rect.getArea();    // OK - getArea() is const
    // rect.setWidth(10);           // ERROR - setWidth() is not const
}

Marking functions as const when they don't modify the object is good practice. It documents your intent, enables the function to work with const objects, and helps the compiler catch accidental modifications. Any member function that only reads data should be marked const.

challenge icon

Challenge

Easy

Let's build a temperature converter that demonstrates when and why to use const member functions. You'll create a class where some methods only read data (and should be const) while others modify the object's state.

You'll create two files to organize your code:

  • Temperature.h: Define a Temperature class that stores a temperature value and provides various ways to read and modify it. Your class should have:
    • A private member celsius (double) to store the temperature
    • A constructor that takes an initial Celsius value
    • A getCelsius() method that returns the stored value — this should be const since it only reads data
    • A getFahrenheit() method that calculates and returns the temperature in Fahrenheit using the formula celsius * 9.0 / 5.0 + 32.0 — also const since it doesn't modify anything
    • A getKelvin() method that returns the temperature in Kelvin using celsius + 273.15 — const as well
    • A setCelsius(double value) method that updates the stored temperature — this cannot be const since it modifies the object
    • A adjustBy(double delta) method that adds the delta to the current temperature — also non-const
  • main.cpp: Demonstrate how const member functions work with both regular and const objects. Read an initial temperature value from input, then:
    • Create a Temperature object with the input value
    • Print "Initial: <celsius>C = <fahrenheit>F = <kelvin>K"
    • Adjust the temperature by 10.0 degrees
    • Print "After adjustment: <celsius>C"
    • Create a helper function void printReadings(const Temperature& temp) that takes a const reference and prints "Reading: <celsius>C, <fahrenheit>F" — this function can only call const methods on temp
    • Call printReadings() with your temperature object
    • Set the temperature to 0.0 (freezing point)
    • Print "Freezing point: <celsius>C = <fahrenheit>F"

Format all temperature values with one decimal place using std::fixed and std::setprecision(1) from <iomanip>.

The key insight here is that printReadings() receives a const reference, so it can only call methods marked as const. This is why properly marking your getter methods as const matters — it enables them to work in contexts where the object cannot be modified.

Cheat sheet

A const member function promises not to modify any member variables of the object. The const keyword is placed after the function's parameter list:

class Rectangle {
    int width;
    int height;
public:
    int getArea() const {      // const member function
        return width * height;  // Reading members is allowed
    }
    
    void setWidth(int w) {     // Non-const - modifies the object
        width = w;
    }
};

Const member functions can only read member variables, not modify them. If you try to modify a member variable inside a const function, the compiler will produce an error.

A const object or const reference can only call const member functions:

void printArea(const Rectangle& rect) {
    std::cout << rect.getArea();    // OK - getArea() is const
    // rect.setWidth(10);           // ERROR - setWidth() is not const
}

Mark functions as const when they don't modify the object. This documents your intent, enables the function to work with const objects, and helps the compiler catch accidental modifications. Any member function that only reads data should be marked const.

Try it yourself

#include <iostream>
#include <iomanip>
#include "Temperature.h"
using namespace std;

// TODO: Implement the Temperature class methods here
// Constructor
Temperature::Temperature(double initialCelsius) {
    // TODO: Initialize celsius
}

// TODO: Implement getCelsius() as const

// TODO: Implement getFahrenheit() as const

// TODO: Implement getKelvin() as const

// TODO: Implement setCelsius(double value)

// TODO: Implement adjustBy(double delta)


// TODO: Create a helper function printReadings that takes a const Temperature& 
// and prints "Reading: <celsius>C, <fahrenheit>F"
// Note: This function can only call const methods on temp!


int main() {
    double initialTemp;
    cin >> initialTemp;

    // Set output formatting
    cout << fixed << setprecision(1);

    // TODO: Create a Temperature object with the input value

    // TODO: Print "Initial: <celsius>C = <fahrenheit>F = <kelvin>K"

    // TODO: Adjust the temperature by 10.0 degrees

    // TODO: Print "After adjustment: <celsius>C"

    // TODO: Call printReadings() with your temperature object

    // TODO: Set the temperature to 0.0 (freezing point)

    // TODO: Print "Freezing point: <celsius>C = <fahrenheit>F"

    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming