-2

Can we incorporate member functions inside a structure in C++? As we do in classes can we put functions inside structures. If yes then what is the fun on keeping both Structures and Classes in C++?

  • Yes. `struct` and `class` are essentially the same. – juanchopanza Jan 13 '14 at 14:55
  • 1
    Similar to http://stackoverflow.com/questions/54585/when-should-you-use-a-class-vs-a-struct-in-c – Yousf Jan 13 '14 at 14:55
  • One common convention is to use `class` for OOP, and `struct` when you are merely grouping together related variables which are accessed directly (e.g. `std::pair`). This works well because `class` is private by default and `struct` is public by default. However, this is not enforced by the language and both can do the same job as each other. – JBentley Jan 13 '14 at 15:52

2 Answers2

2

Can we incorporate member functions inside a structure in C++?

Yes. A class is a class, whether it's declared with the class or struct keyword. The only difference is the default accessibility: public for struct, and private for class.

If yes then what is the fun on keeping both Structures and Classes in C++?

A historical oddity. The class keyword was added to make C with Classes (as C++ was originally called) feel more object-orienty; but no-one saw any reason to prevent traditional struct types from behaving just like the new class types, so we've ended up with two more-or-less equivalent words for the same thing.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
0

One obvious answer is that "struct" was included in the standard to give backward compatibility to C.

To allow forward-declared structs in a C interface which underneath is implemented by a C++ class they allowed struct to be a class too with all the features.

In other words, you can publish an interface that can be called from C code:

struct Foo;

#ifdef __cplusplus 
  extern "C" { // to use with C or C++
#endif

void myFunc1( struct Foo * );
int myFunc2( const struct Foo * );

#ifdef __cplusplus 
   }
#endif

Then in your implementation (in C++)

 struct Foo
 {
    private:
       int myMember;
    public:
       void myFunc1();
       int myFunc2() const;
 };

 void myFunc1( Foo * foo ) { foo->myFunc1(); }
 int myFunc2( Foo const* foo ) { return foo->myFunc2(); }

Your class is usable not only from C libraries but C++ libraries that are possibly not binary-compatible with yours (but are with C), from scripting languages that have bindings with C, etc.

CashCow
  • 30,981
  • 5
  • 61
  • 92