I am learning C++ using the resources listed here. In particular, i read that we can use the auto type specifier as the return type of a function. So to get clarity over the concept, i tried the following example:
header.h
#pragma once
struct S
{
auto f();
};
source.cpp
#include "header.h"
auto S::f()
{
return 4;
}
main.cpp
#include <iostream>
#include "header.h"
int main()
{
S s;
s.f();
return 0;
}
But this gives me error saying:
main.cpp:7:9: error: use of ‘auto S::f()’ before deduction of ‘auto’
7 | s.f();
| ^
My question is why am i getting this error and how to solve this.
The problem is that the function definition must be visible at any point where the function(with auto
return type as in your case) is used. Since you've defined(implemented) that member function inside a source file(.cpp), it is not visible when the call expression s.f()
is encountered.
To solve this you can put the implementation of the member function inside the header and make use of inline
keyword as shown below:
header.h
#pragma once
struct S
{
auto f();
};
inline auto S::f() //note the use of inline to avoid multiple definition error
{
return 4;
}
Note that we've used inline
because we've implemented the member function in a header file which will be included in many other source files. That is, to avoid multiple definition error.