in programming, function that does not interact with global state
In computer programming, a pure function is a function that has the following properties: the function return values are identical for identical arguments (no variation with local static variables, non-local variables, mutable … Wikipedia
🌐
Wikipedia
en.wikipedia.org › wiki › Pure_function
Pure function - Wikipedia
September 24, 2025 - Nevertheless, there is a sense in which a function can perform input or output and still be pure, if the sequence of operations on the relevant I/O devices is modeled explicitly as both an argument and a result, and I/O operations are taken to fail when the input sequence does not describe the operations actually taken since the program began execution. The second point ensures that the only sequence usable as an argument must change with each I/O action; the first allows different calls ...
Top answer
1 of 8
130

They can result if you try to make a virtual function call from a constructor or destructor. Since you can't make a virtual function call from a constructor or destructor (the derived class object hasn't been constructed or has already been destroyed), it calls the base class version, which in the case of a pure virtual function, doesn't exist.

class Base
{
public:
    Base() { reallyDoIt(); }
    void reallyDoIt() { doIt(); } // DON'T DO THIS
    virtual void doIt() = 0;
};

class Derived : public Base
{
    void doIt() {}
};

int main(void)
{
    Derived d;  // This will cause "pure virtual function call" error
}

See also Raymond Chen's 2 articles on the subject

2 of 8
73

As well as the standard case of calling a virtual function from the constructor or destructor of an object with pure virtual functions you can also get a pure virtual function call (on MSVC at least) if you call a virtual function after the object has been destroyed. Obviously this is a pretty bad thing to try and do but if you're working with abstract classes as interfaces and you mess up then it's something that you might see. It's possibly more likely if you're using referenced counted interfaces and you have a ref count bug or if you have an object use/object destruction race condition in a multi-threaded program... The thing about these kinds of purecall is that it's often less easy to fathom out what's going on as a check for the 'usual suspects' of virtual calls in ctor and dtor will come up clean.

To help with debugging these kinds of problems you can, in various versions of MSVC, replace the runtime library's purecall handler. You do this by providing your own function with this signature:

int __cdecl _purecall(void)

and linking it before you link the runtime library. This gives YOU control of what happens when a purecall is detected. Once you have control you can do something more useful than the standard handler. I have a handler that can provide a stack trace of where the purecall happened; see here: http://www.lenholgate.com/blog/2006/01/purecall.html for more details.

(Note you can also call _set_purecall_handler() to install your handler in some versions of MSVC).

Discussions

ELI5: what the heck is a "pure virtual function" in c++, and why do things crash when they call one?
A pure virtual function is a function that is defined on a class that does not have a default implementation. It is dependent on a subclass to provide an implementation. Depending on memory/pointer shenigans, the subclass implementation can be lost, and cause crashes (mostly due to mismanagement of pointer arithmetic and/or freed memory, sometimes calling from class constructor because it's written wrongly). For example, Animals may have a function called "breathe", there is no default implementation as it can be done through gills, or lungs, or whatever. It is up to a more concrete implementation, like Human, of "breathe" to supply the details of how it works through lungs, cardio system, etc. In the mentioned crashes, somehow Animal does not have a subclass property like Human associated with it, so it calls through and crashes because the base Animal implementation does not know how to breathe. More on reddit.com
🌐 r/explainlikeimfive
39
57
November 30, 2024
functional programming - Can a pure function call external function? - Stack Overflow
Pure functions always give the same result for any given input, no matter what the current program state.. Methods can be viewed as functions which are passed their object as a hidden parameter. To be pure, the method must not access any implicit state (nor may they call any other methods/functions ... More on stackoverflow.com
🌐 stackoverflow.com
September 15, 2016
Is a function getting a value from another function considered pure?
That depends on what the other function does, and what the calling function does. Impurity is infectious, purity isn't. Calling a pure function doesn't change the purity of the calling function. More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
March 14, 2016
functional programming - Should a pure function take all of the functions it calls as arguments? - Computer Science Stack Exchange
After Wikipedia, if a function is pure, then: [it] always evaluates the same result value given the same argument value(s). So: if a function, let's call it f, calls another function, g, then i... More on cs.stackexchange.com
🌐 cs.stackexchange.com
July 28, 2016
🌐
React
react.dev › learn › keeping-components-pure
Keeping Components Pure – React
Pure functions only calculate, so calling them twice won’t change anything—just like calling double(2) twice doesn’t change what’s returned, and solving y = 2x twice doesn’t change what y is. Same inputs, same outputs.
🌐
Reddit
reddit.com › r/explainlikeimfive › eli5: what the heck is a "pure virtual function" in c++, and why do things crash when they call one?
r/explainlikeimfive on Reddit: ELI5: what the heck is a "pure virtual function" in c++, and why do things crash when they call one?
November 30, 2024 -

title, for context, i noticed a payday 2 crash log of mine had that as the crash reason, and any explanation i can find on c++ forums is very confusing, and overwhelms me instantly lol

Top answer
1 of 10
11
A pure virtual function is a function that is defined on a class that does not have a default implementation. It is dependent on a subclass to provide an implementation. Depending on memory/pointer shenigans, the subclass implementation can be lost, and cause crashes (mostly due to mismanagement of pointer arithmetic and/or freed memory, sometimes calling from class constructor because it's written wrongly). For example, Animals may have a function called "breathe", there is no default implementation as it can be done through gills, or lungs, or whatever. It is up to a more concrete implementation, like Human, of "breathe" to supply the details of how it works through lungs, cardio system, etc. In the mentioned crashes, somehow Animal does not have a subclass property like Human associated with it, so it calls through and crashes because the base Animal implementation does not know how to breathe.
2 of 10
3
A pure virtual function is a function that the code says exists, but has no definition. The definition is expected to be supplied by other related classes. If I had a class called "Shape" then I would likely want to make sure that every type of Shape has some way to Draw itself, so I make a function called "Draw" but I don't know how to draw a generic shape, so I don't give it a definition. The Draw method within Shape is purely virtual I later make a Circle class and tell the code it's a type of Shape. The coding tool will tell me to make a definition for the Draw function if I want to classify a Circle as a Shape. Well, I know how to draw a circle, you fill in all the pixels which are a fixed distance from the center, so I can now make a proper Draw function for the Circle.
🌐
Medium
medium.com › javascript-scene › master-the-javascript-interview-what-is-a-pure-function-d1c076bec976
Master the JavaScript Interview: What is a Pure Function? | by Eric Elliott | JavaScript Scene | Medium
August 30, 2025 - Pure functions can help you avoid those kinds of bugs. With our `double()` function, you can replace the function call with the result, and the program will mean the same thing — `double(5)` will always mean the same thing as `10` in your program, regardless of context, no matter how many times you call it or when.
🌐
DEV Community
dev.to › alexkhismatulin › pure-functions-explained-for-humans-1j3c
Pure Functions Explained for Humans - DEV Community
December 21, 2021 - A function can be called pure if it returns the same output given the same input every time you call it, doesn't consume or modify other resources internally, and doesn't change its inputs.
Find elsewhere
🌐
SitePoint
sitepoint.com › blog › rails tutorials › functional programming: pure functions
Functional Programming: Pure Functions — SitePoint
November 11, 2024 - When you call a method on an object, it’s as if the object is passed to the function as the argument self. It’s another value the function can rely on to compute its result. ... It turns a string into uppercase, but the original string remains untouched. upcase didn’t do anything else, such as write to a log file or read mouse input. upcase is pure.
🌐
Scala Documentation
docs.scala-lang.org › overviews › scala-book › pure-functions.html
Pure Functions | Scala Book | Scala Documentation
In Functional Programming, Simplified, Alvin Alexander defines a pure function like this: The function’s output depends only on its input variables ... It doesn’t have any “back doors”: It doesn’t read data from the outside world (including the console, web services, databases, files, etc.), or write data to the outside world · As a result of this definition, any time you call a pure function with the same input value(s), you’ll always get the same result.
🌐
Chatbotkit
chatbotkit.com › tutorials › how to use pure function calling with caller handling
How to Use Pure Function Calling with Caller Handling
January 26, 2026 - This tutorial demonstrates how to implement "pure" function calling in ChatBotKit, where functions are defined without handlers or static results, giving the caller complete control over function execution.
🌐
Medium
medium.com › better-programming › what-is-a-pure-function-3b4af9352f6f
What Is a Pure Function?. Pure functions in programming and their… | by Devin Soni | Better Programming
December 8, 2019 - What Is a Pure Function? Pure functions in programming and their benefits Definition In programming, a pure function is a function that has the following properties: The function always returns the …
🌐
Ada Beat
adabeat.com › home › pure functions in functional programming
Pure functions in Functional Programming - Ada Beat
May 7, 2024 - No side effects: Pure functions do not modify external state, variables, or any data outside their own scope. They encapsulate their logic, making it easier to understand and debug.
Top answer
1 of 11
142

The dollarToEuro's return value depends on an outside variable that is not an argument; therefore, the function is impure.

If the answer is NO, how then can we refactor the function to be pure?

One option is to pass in exchangeRate. This way, every time arguments are (something, somethingElse), the output is guaranteed to be something * somethingElse:

const exchangeRate =  fetchFromDatabase(); // evaluates to say 0.9 for today;

const dollarToEuro = (x, exchangeRate) => {
  return x * exchangeRate;
};

Note that for functional programming, you should avoid let - always use const to avoid reassignment.

2 of 11
84

Technically, any program that you execute on a computer is impure because it eventually compiles down to instructions like “move this value into eax” and “add this value to the contents of eax”, which are impure. That's not very helpful.

Instead, we think about purity using black boxes. If some code always produces the same outputs when given the same inputs then it's considered to be pure. By this definition, the following function is also pure even though internally it uses an impure memo table.

const fib = (() => {
    const memo = [0, 1];

    return n => {
      if (n >= memo.length) memo[n] = fib(n - 1) + fib(n - 2);
      return memo[n];
    };
})();

console.log(fib(100));

We don't care about the internals because we are using a black box methodology for checking for purity. Similarly, we don't care that all code is eventually converted to impure machine instructions because we're thinking about purity using a black box methodology. Internals are not important.

Now, consider the following function.

const greet = name => {
    console.log("Hello %s!", name);
};

greet("World");
greet("Snowman");

Is the greet function pure or impure? By our black box methodology, if we give it the same input (e.g. World) then it always prints the same output to the screen (i.e. Hello World!). In that sense, isn't it pure? No, it's not. The reason it's not pure is because we consider printing something to the screen a side effect. If our black box produces side effects then it is not pure.

What is a side effect? This is where the concept of referential transparency is useful. If a function is referentially transparent then we can always replace applications of that function with their results. Note that this is not the same as function inlining.

In function inlining, we replace applications of a function with the body of the function without altering the semantics of the program. However, a referentially transparent function can always be replaced with its return value without altering the semantics of the program. Consider the following example.

console.log("Hello %s!", "World");
console.log("Hello %s!", "Snowman");

Here, we inlined the definition of greet and it didn't change the semantics of the program.

Now, consider the following program.

undefined;
undefined;

Here, we replaced the applications of the greet function with their return values and it did change the semantics of the program. We are no longer printing greetings to the screen. That's the reason why printing is considered a side effect, and that's why the greet function is impure. It's not referentially transparent.

Now, let's consider another example. Consider the following program.

const main = async () => {
    const response = await fetch("https://time.akamai.com/");
    const serverTime = 1000 * await response.json();
    const timeDiff = time => time - serverTime;
    console.log("%d ms", timeDiff(Date.now()));
};

main();

Clearly, the main function is impure. However, is the timeDiff function pure or impure? Although it depends upon serverTime which comes from an impure network call, it is still referentially transparent because it returns the same outputs for the same inputs and because it doesn't have any side effects.

zerkms will probably disagree with me on this point. In his answer, he said that the dollarToEuro function in the following example is impure because “it depends upon the IO transitively.”

const exchangeRate =  fetchFromDatabase(); // evaluates to say 0.9 for today;

const dollarToEuro = (x, exchangeRate) => {
  return x * exchangeRate;
};

I have to disagree with him because the fact that the exchangeRate came from a database is irrelevant. It's an internal detail and our black box methodology for determining the purity of a function doesn't care about internal details.

In purely functional languages like Haskell, we have an escape hatch for executing arbitrary IO effects. It's called unsafePerformIO, and as the name implies if you do not use it correctly then it's not safe because it might break referential transparency. However, if you do know what you're doing then it's perfectly safe to use.

It's generally used for loading data from configuration files near the beginning of the program. Loading data from config files is an impure IO operation. However, we don't want to be burdened by passing the data as inputs to every function. Hence, if we use unsafePerformIO then we can load the data at the top level and all our pure functions can depend upon the immutable global config data.

Note that just because a function depends upon some data loaded from a config file, a database, or a network call, doesn't mean that the function is impure.

However, let's consider your original example which has different semantics.

let exchangeRate =  fetchFromDatabase(); // evaluates to say 0.9 for today;

const dollarToEuro = (x) => {
  return x * exchangeRate;
};

dollarToEuro(100) //90 today

dollarToEuro(100) //something else tomorrow

Here, I'm assuming that because exchangeRate is not defined as const, it's going to be modified while the program is running. If that's the case then dollarToEuro is definitely an impure function because when the exchangeRate is modified, it'll break referential transparency.

However, if the exchangeRate variable is not modified and will never be modified in the future (i.e. if it's a constant value), then even though it's defined as let, it won't break referential transparency. In that case, dollarToEuro is indeed a pure function.

Note that the value of exchangeRate can change every time you run the program again and it won't break referential transparency. It only breaks referential transparency if it changes while the program is running.

For example, if you run my timeDiff example multiple times then you'll get different values for serverTime and therefore different results. However, because the value of serverTime never changes while the program is running, the timeDiff function is pure.

🌐
Scaler
scaler.com › home › topics › what is pure function in javascript?
What is Pure Function in JavaScript? - Scaler Topics
October 17, 2022 - A pure function in JavaScript is a function that returns the same result if the same arguments(input) are passed in the function. Let's see what makes a function pure in detail: The return value of the function on the function call should only ...
🌐
GeeksforGeeks
geeksforgeeks.org › c language › pure-functions
Pure Functions - GeeksforGeeks
July 23, 2025 - A function is called pure function ... an argument (or global variable) or outputting something. The only result of calling a pure function is the return value....
🌐
Reddit
reddit.com › r/unrealengine › what exactly can and cannot be a "pure" function
r/unrealengine on Reddit: What EXACTLY can and cannot be a "pure" function
June 8, 2023 -

My understanding has always been that if it doesnt change anything outside of itself it can be pure. On asking people about this in the past they have responded with "basically, yes".

But what about none-basically? Is there more to it than that?

Top answer
1 of 3
9
The definition is oddly blurred as there is a computer science definition for pure functions which is where the name and inspiration comes from- but Unreal doesn't really follow it and has a handwavy overlapping usage instead. The traditional definition requires a pure function to essentially only rely on the inputs provided to it, with no reliance on either internal or external state (which can change), and to always return the same result for the same input. This rules out a lot of the standard real-world Unreal Engine uses though. Calls to 'Get Actor Forward Vector' rely on external state in that it's relying on the Actor's Transform, and 'Random Integer' relies on the internal state of the random number generator it's using, and will even change this state as generating a random number will advance the generator. Instead Unreal Engine replaces this with a simpler definition: A Pure function in Blueprint is one which has no execution pin, and is very easy to misuse. Now the intent is that you're going to be limiting your interaction with external state but you're not restricted to it, you can move an Actor inside a Pure function but you shouldn't. Generally I try to keep Pure functions very simple, as close to 'true pure' as possible in that I may read from external state (a la 'Get Actor Forward Vector') but will not change it (...so no pure 'Set Actor Forward Vector'). ~~Also remember that a pure node connected to multiple inputs will be evaluated multiple times- and this can be a gotcha for both understanding and performance without knowing what you're doing. For a 'confusing flow' example imagine I was being lazy and writing an Asteroids control method in a single function- so I move the ship, rotate the ship, and then use a trace to detect any asteroids ahead and damage them. I start with 'Get Actor Forward Vector' to get the heading to move it, then turn it, then do the rotation, and then call 'Get Actor Forward Vector' to find the new heading for the laser- but as I already have a 'Get Actor Forward Vector' node I plug that into the Trace. This actually works fine, the forward vector is evaluated twice at different points in the execution and gives different results, but the graph looks weird in that a single node is giving two different values. Better would be to have another 'Get Actor Forward Vector' node for the trace, keep it separate and make it clear there's no dependency or caching here.~~ This caching brings out another problem though- performance. Imagine you have an inventory system and have a 'Get Total Weight Carried' function on it, this is as pure as 'Get Actor Forward Vector' (relies on internal state, doesn't change it) so you're willing to make it pure. You then use it, connecting the output to eight different functions to handle everything from UI to character speed reduction. Despite there only being one 'Get Total Weight Carried' node each time the node is called it evaluates again, and as it's walking through the entire inventory and calculating weight this can be expensive in terms of performance. If this had not been a Pure node it would have been evaluated once, when execution hit it, even if we plugged the output into the same eight inputs. When dealing with expensive nodes either don't make them pure, in order to make sure that repeated calls are more obvious, or make certain to cache the result so that it's only run once. EDIT: Bah, it looks like I messed up my understanding of pure functions being evaluated multiple times, see here . Going to tweak my post where I was wrong but wanted quick fix here.
2 of 3
2
I use pure functions to get data, I use impure functions to set it. That’s basically the line I draw and it works fine. You can also use pure functions to coerce values. Like if you have first name in one variable and last name in another then maybe you want to write a pure function that appends the last name to the first name and returns the newly combined string as a full name value.
🌐
freeCodeCamp
freecodecamp.org › news › what-is-a-pure-function-in-javascript-acb887375dfe
What Is a Pure Function in JavaScript?
January 3, 2019 - The variable, person, has been forever changed because our function introduced an assignment statement. Shared state means impureAssoc's impact isn’t fully obvious anymore. Understanding its effect on a system now involves tracking down every variable it’s ever touched and knowing their histories. Shared state = timing dependencies. We can purify impureAssoc by simply returning a new object with our desired properties. const pureAssoc = (key, value, object) => ({ ...object, [key]: value }); const person = { name: 'Bobo' }; const result = pureAssoc('shoeSize', 400, person); console.log({ person, result });