Reputation: 105
I am relatively new to programming, so please pardon me as this is a very simple and basic question. I am working in visual studio 2019. I made a class Sphere and inside it I created a structure:
struct point{
vec3 coordinate; //I am using glm library
};
struct triangle{
point p1, p2, p3;
};
Now when I declare a function returning a pointer to struct triangle:
// in the .h file
triangle* returnTriangle(triangle T);
//--------------------------------------------------------
//and later in the .cpp file
triangle* Sphere:: returnTriangle(triangle T) //This definition was made by the IDE itself.
{
//code returning a triangle* variable
}
I get an error:
Identifier triangle is undefined. Declaration is incompatible with Sphere::returnTriangle();
I get this error only for the triangle used in the function definition that is if I use triangle inside the function, it doesn't show this error.
I have included the Sphere.h file in Sphere.cpp, so why is triangle still undefined?
EDIT:
The complete error message:
E0020 identifier triangle is undefined.
//The line of function definition that is triangle* //Sphere::returnTriangle(triangle T)
//{code}
E0147 declaration is incompatible with Sphere::triangle* Sphere::print
Minimum reproducable example: just make a class and create a structure (say triangle) you wish. Then declare a function inside the class:
triangle* print();
Then define the function in the .h file:
triangle* Sphere::print()
{
//some code
}
Upvotes: 0
Views: 63
Reputation: 1110
I will sum it up:
It you defined an inner-struct triangle
(you should call it Triangle
by the way!). In order to call it from outside the class you must specify its complete name, thus, the following signature is not valid:
Triangle* Sphere::returnTriangle(Triangle T)
Because it is looking for a struct with a name Triangle
, but there is no struct with this name. The struct is called Sphere::Triangle
which isn't the same as Triangle
.
When you are inside a context of the class (for example, when writing the body of member method), you don't need to specify the location, since in this context, Sphere
is included in "namespaces" which the compiler "knows", and you don't need to explicitly tell it to look inside of the Sphere
class.
This behavior is similar to namespace
. This is a tool to distinguish between different signatures. For example, STL has an implementation of vector
, but assume that we want to write a new implementation of vector
. We can do so by declaring this class in our namespace, and we get two different signatures:
std::vector
vs:
our_namespace::vector
and these are not the same!
Upvotes: 2