Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of class and struct [duplicate]

Tags:

c++

class

struct

Possible Duplicates:
When should you use a class vs a struct in C++?
What are the differences between struct and class in C++

struct X{

};

class X{

};

in C++, Same task can be done by class as well as struct. My question is where should I use class and where struct?

like image 620
sukumar Avatar asked Jan 19 '23 01:01

sukumar


1 Answers

The differences between a struct and class in C++ are:

  • Members of a class are private by default, whereas members of a struct are public by default.
  • Similarly, inheritance between classes is also private by default, and inheritance between structs is public by default.

But basically anywhere you use a struct you could use a class, and vice versa, so it's really up to you what to use. Conventionally, when you have methods, it is more common to use a class, and when you only have data, structs are more commonly used.

I would say that if you want all the data members to be public, and you have no methods, then use a struct. Otherwise use a class. But that's just personal preference.

like image 82
David Heffernan Avatar answered Jan 31 '23 16:01

David Heffernan