116

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?

John
  • 4,276
  • 11
  • 35
  • 43

2 Answers2

182

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
fejese
  • 4,481
  • 4
  • 27
  • 36
Luchian Grigore
  • 245,575
  • 61
  • 446
  • 609
46

Structs can have functions just like classes. The only difference is that they are public by default:

struct A {
    void f() {}
};

Additionally, structs can also have constructors and destructors.

struct A {
    A() : x(5) {}
    ~A() {}

    private: int x;
};
David G
  • 90,891
  • 40
  • 158
  • 247