Thursday, May 19, 2016

Transition from C to C++: Struct vs. Class

Here, I will write about some of the changes that a C programmer should be aware of when transitioning into C++.

Some key differences between class and struct:
  1. In C, struct holds a chunk of data. In C++, class also holds a chunk of data but in addition it also defines some methods related to it.
  2. All the fields in struct is visible to anyone, while the fields are private by default in class.
  3. In C, you need the keyword struct as the identifier, whereas in C++ you do not need the keyword class.
  4. In C++, you also have a static field. However, it needs to be declared globally; Otherwise you will get a linker error.
The following code summarizes the differences:

// C++
class Class {
int data1; // private by default
char data2; // private by default
   static int length; // static variable
class Class* method1() {...}; // public method that returns pointer to Class object.
Class* method2() {...}; // class identifier is not necessary

int Class::length; // must declare it globally

// C
struct Struct {
int data1; // public by default
char data2; // public by default
struct Struct* func1() {...} // a function that returns a pointer to struct Struct. struct identifier is necessary

No comments:

Post a Comment