Some key differences between class and struct:
- 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.
- All the fields in struct is visible to anyone, while the fields are private by default in class.
- In C, you need the keyword struct as the identifier, whereas in C++ you do not need the keyword class.
- 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
public:
static int length; // static variable
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
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