"returning" an object without including it in C ++

I hope this has not been asked too many times, I tried to search, but could not find anything (maybe I just did not know how to correctly express it). Simple question:

I have a vec3 class that has 3 fields x, y and z in it there is a flatten function that I want to return a vec2 object (or something from which vec2 object can be created) that has only x and y fields. Since this is the only function of the vec3 class that is related to vec2, I would not want to include vec2. Is there a better way to return such a simple object (two two-local ones) without any inclusions?

I was thinking about returning a pointer, but what happens if I do this:

vec2 v2 = vec3(x,y,z).flatten(); // vec3(x,y,z) is the constructor

Will temporary objects vec3 x and y still exist when v2 tries to build from them? In this case, it vec2 = double*will be defined in the class vec2.

vec3 and vec2 are as follows:

class vec3{
   double x,y,z;
}

Will xy and z be sequential in memory? I would suggest no.

Thank you for your time.

+4
source share
1 answer

You only need a partial declaration for the return type:

Vec3.h:

// No #include "Vec2.h" !

class vec2; // Partial declaration

class vec3 {
    //...
    vec2 flatten() const;
    //...
};

Vec3.cpp:

#include "Vec2.h"

vec2 vec3::flatten() const {
    //...
}
+5

All Articles