I'm looking at the following tutorial: http://www.videotutorialsrock.com/opengl_tutorial/animation/home.php
This person has a vector class:
class Vec3f {
private:
float v[3];
public:
Vec3f();
Vec3f(float x, float y, float z);
float &operator[](int index);
float operator[](int index) const;
Vec3f operator*(float scale) const;
Vec3f operator/(float scale) const;
Vec3f operator+(const Vec3f &other) const;
Vec3f operator-(const Vec3f &other) const;
Vec3f operator-() const;
const Vec3f &operator*=(float scale);
const Vec3f &operator/=(float scale);
const Vec3f &operator+=(const Vec3f &other);
const Vec3f &operator-=(const Vec3f &other);
float magnitude() const;
float magnitudeSquared() const;
Vec3f normalize() const;
float dot(const Vec3f &other) const;
Vec3f cross(const Vec3f &other) const;
};
With an example definition:
Vec3f Vec3f::operator*(float scale) const {
return Vec3f(v[0] * scale, v[1] * scale, v[2] * scale);
}
I'm confused on why this works. Shouldn't this immediately cause a segmentation fault? The return value is on the stack and should get deleted upon termination of all of these functions. Why does it work? Is my understanding of stack vs heap incorrect?
EDIT: I am basing my understanding from this: How to return a class object by reference in C++?