Saturday, May 5, 2007

C++ Structure vs C++ Class

C++ programming language provides structure and class to create problem-oriented datatypes.Instance of these datatypes are known as objects.

C++ Structure and C++ class are exactly same except default access specifier of their members i.e. in C++ Structure all members are public by default while in Class all are private.

For example in following code , the class C is equivalent to structure S

class C
{
//default access specifier is private
int num;

public:
void setNum(int n)
{
Num = n;
}
}

struct S
{
//default access specifier is public
void setNum(int n)
{
Num = n;
}

private:
int num;
}

Hence we can see here that the difference in both is only access specifier, but as security is concern, this is a big drawback of structure.Because by default all the members are exposed to outside world. That is the one main reason, why programmers are hesitant to use structure.In turn, class encourages encapsulation/data-hiding by default.So my recommendation is use class, forget structure.