Today, I was curious to find some of differences between a structure and a class, in C++. So, I found some of the differences:
- In a structure, by default members are public while private in class.
- Inheritance in case of a structure is public by default, while private in case of class.
- Classes can take part in templates, while structures cannot.
click here to see that a struct cannot be used in place of class in case of template.
http://ideone.com/p5G57
template<struct T> void fun(T i)
{
cout<<i<<endl;
}
int main()
{
int i=10;
fun<int>(i);
return 0;
}
It gives the errors:
prog.cpp:4: error: ‘struct T’ is not a valid type for a template constant parameter
prog.cpp: In function ‘void fun(T)’:
prog.cpp:4: error: ‘i’ has incomplete type
prog.cpp:4: error: forward declaration of ‘struct T’
prog.cpp: In function ‘int main()’:
prog.cpp:12: error: no matching function for call to ‘fun(int&)’
However, if struct is replaced with class, it works perfectly. see here: http://ideone.com/K8bFn
Apart from these above differences, when I replace class with struct in my code, the code works perfectly without making any further changes.
Now, I want to know, are there more differences, that I am missing and I should know?
There’s no other difference, but the third one you specify isn’t correct:
In case of templates, the
classkeyword is just syntactic sugar, it doesn’t mean the type has to be an actual class. Generally, programmers prefertypenamefor basic types andclassfor classes or structs, but that’s just by convention.Other than that, you can use both
classandstructto specialize templates.