Function for C ++ Structure

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

struct foo { int bar; }; 

Can functions also be defined for a structure? How will we use these features?

+48
c ++ function struct
Oct 29 '12 at 16:41
source share
2 answers

Yes, a struct is identical to class , with the exception of the default access level (member and inherited). (and the class has additional meaning when used with a template)

Each functionality supported by the class is supported by the structure. You would use methods the same way you would 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 
+82
Oct 29
source share

Structures can have functions similar to classes. The only difference is that they are publicly available by default:

 struct A { void f() {} }; 

In addition, structures can also have constructors and destructors.

 struct A { A() : x(5) {} ~A() {} private: int x; }; 
+19
Oct 29 '12 at 16:46
source share



All Articles