1. Member functions inside the structure: Structures in C cannot have member functions inside a structure but Structures in C++ can have member functions along with data members.
No, you can't. Structs can only contain variables inside, storing function pointers inside the struct can give you the desired result. Show activity on this post. No, but you can in c++ struct!
If a struct is declared in a header file in C++, you must include the header file everywhere a struct is used and where struct member functions are defined. The C++ compiler will give an error message if you try to call a regular function, or call or define a member function, without declaring it first.
Structure is a UDT in C++ too but you can have functions inside structures. You cannot declare a function in a structure as the structure is itself included in a function i.e. int main() or void main() or in any other function you may declare, and you cannot declare a funtion into another function.
What I am trying to achieve is mainly returning an unnamed struct from a function in C++11. In C++14, I can do this by defining the function inline and having auto
as return type, like this:
auto func()
{
struct
{
int member;
} ret;
// set ret.member
return ret;
}
However, C++11 doesn't support deducing the return type of a normal (non-lambda) function, and this only works in C++14 when the definition is done inline.
I tried the following two variations of declaring the struct in the function declaration:
auto func() -> struct { int member; };
struct { int member; } func();
Is this simply impossible to do with C++11? If so, does someone know whether this was disallowed on purpose or just nobody thought of this new use of automatically deduced types (because this only works with the functions return value being assigned to an auto
variable)?
And finally, is there any other way to achieve something similar to this? I am aware of std::tuple
, but I want to name the values; and in my use case the struct type is definitely only useful as return type of this one function, so why name it?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With