Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

structure vs class

Tags:

c++

Today, I was curious to find some of differences between a structure and a class, in C++. So, I found some of the differences:

  1. In a structure, by default members are public while private in class.
  2. Inheritance in case of a structure is public by default, while private in case of class.
  3. 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?

like image 262
Green goblin Avatar asked Jun 20 '12 11:06

Green goblin


People also ask

What is the difference between class and structure in programming?

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.

What is difference between structure and class in C++?

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.


1 Answers

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.

like image 173
Luchian Grigore Avatar answered Oct 18 '22 04:10

Luchian Grigore