Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can C++ struct have member functions?

I was pretty confused about the difference between struct and class as I seemed to see them used for pretty much the same things. I googled the differences and the only answer I saw was that structs have public members by default and classes have private members by default. However, my lecturers have just told me that structs cannot contain member functions. But I have seen many threads on the internet where people include member functions in structs and specifically say that it is alright to do so.

My lecturers seem adamant that structs by definition cannot have functions, so what is going on? The only thing I could think of is that maybe the compiler changes functions within a struct to something else so that they technically don't contain functions... Is there a clear answer to these contradictions?

like image 490
Sam Avatar asked Jun 13 '14 02:06

Sam


People also ask

Can structs have function members?

Can C++ struct have member functions? Yes, they can.

Can a struct have itself as a member?

A structure T cannot contain itself.

Can struct have class member?

Yes, you can. The pointer to the class member variable is stored on the stack with the rest of the struct's values, and the class instance's data is stored on the heap. Structs can also contain class definitions as members (inner classes).


2 Answers

I googled the differences and the only answer I saw was that structs have public members by default and classes have private members by default.

Yes, this is correct. In addition, bases of a struct are inherited publicly by default, whereas bases of a class are inherited privately by default.

Declaring a function as a member of a struct has precisely the same semantics as declaring a function as a member of a class, except for the difference you've noted. In each case they are called member functions.

like image 78
Brian Bi Avatar answered Sep 20 '22 07:09

Brian Bi


C++ structs can definitely have member functions. C structs, on the other hand, are a much different beast -- they're essentially arrays that provide names and type information for certain indicies.

like image 27
Patrick Collins Avatar answered Sep 21 '22 07:09

Patrick Collins