How does const actually work?

I’m having some trouble understanding const. For example,

void UBullCowCartridge::OnInput(const FString& Input)

doesn’t the variable Input change every time we press enter? How is it constant?
Or here,

bool UBullCowCartridge::IsIsogram(FString Word) const

How is it const? This function checks many strings if they’re isograms.

doesn’t the variable Input change every time we press enter?

Yes but it can’t be modified by this function. Reference to const basically means “read only”

void UBullCowCartridge::OnInput(const FString& Input)
{
    Input = TEXT("Bob"); // compile time error. Can't modify Input
}

How is it const? This function checks many strings if they’re isograms.

But it doesn’t modifiy UBullCowCartridge at all. const member functions mean it doesn’t modify the object that calls it

class Example
{
    int Value = 10;
    void Foo() const
    {
        Value = 20; // Compile time error, can't modify data members
    }
];

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms