Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function for C++ struct

Usually we can define a variable for a C++ struct, as in

struct foo {   int bar; }; 

Can we also define functions for a struct? How would we use those functions?

like image 995
John Avatar asked Oct 29 '12 16:10

John


People also ask

Can you have a function in a struct in C?

You cannot have functions in structs in C; you can try to roughly simulate that by function pointers though.

Can you define a function in struct?

No, you can't. Structs can only contain variables inside, storing function pointers inside the struct can give you the desired result.

Can a function return a struct?

Return struct from a functionThe function returns a structure of type struct student . The returned structure is displayed from the main() function. Notice that, the return type of getInformation() is also struct student .


1 Answers

Yes, a struct is identical to a class except for the default access level (member-wise and inheritance-wise). (and the extra meaning class carries when used with a template)

Every functionality supported by a class is consequently supported by a struct. You'd use methods the same as you'd use them for a class.

struct foo {   int bar;   foo() : bar(3) {}   //look, a constructor   int getBar()    {      return bar;    } };  foo f; int y = f.getBar(); // y is 3 
like image 105
Luchian Grigore Avatar answered Sep 22 '22 04:09

Luchian Grigore