Sunday, June 14, 2009

Difference between a struct and a class

This is a common question in an interviews. Mostly an interviewer asks about the difference between a struct and a class ? In c++, difference is that struct has by-default public access to data-members and a class has by-default private access to data-members. And inheritance is by default public in case of a struct and private in case of a class. That is it!
Interviewer asks, 'What else?'
Above differences looks sufficient, but, there is more that interviewer expects. What is that ?

We cannot have,
template <\struct type\> /* ignore slash */
struct ABC{...};

Like,
template <\class type\> /* ignore slash */
class ABC{...};
Because templates do not offer backward C compatibilty.

He asks again, 'What else ?' { still more expecting ?...}
The use of one-element array at the end of a struct to allow individual struct objects to address variable-size array:
strcut ABC
{
int s;
char arr[1];
};

struct ABC* pAbc = (struct ABC*)malloc(sizeof(struct ABC)+strlen(string)+1);
strcpy(pAbc->arr, string);
This may or may nto translate well when placed within a class declaration that specifies multiple access sections containing data, derives from another class, or defines virtual functions.

Otherwise, struct is same as class... struct offers virtual functions, inheritance, ctor-dtor..everything what class offers.

No comments:

Post a Comment