Today, I was curious to find some of differences between a structure and a class, in C++. So, I found some of the differences:
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?
A class is a user-defined blueprint or prototype from which objects are created. Basically, a class combines the fields and methods(member function which defines actions) into a single unit. A structure is a collection of variables of different data types under a single unit.
The C++ class is an extension of the C language structure. Because the only difference between a structure and a class is that structure members have public access by default and class members have private access by default, you can use the keywords class or struct to define equivalent classes.
There's no other difference, but the third one you specify isn't correct:
Class can take part in template while structures cannot.
In case of templates, the class
keyword is just syntactic sugar, it doesn't mean the type has to be an actual class. Generally, programmers prefer typename
for basic types and class
for classes or structs, but that's just by convention.
Other than that, you can use both class
and struct
to specialize templates.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With