Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

struct vs class

Status
Not open for further replies.

javaguy1

Programmer
May 14, 2003
136
US
im fairly new to C++ and learned Java first. im wondering when and why i would choose to use a struct over a class.
 
If I remember correctly a struct can contain only data objects, but a class can contain data objects (properties) and methods.
 
No, a struct can have anything a class can.

The one and only difference is that, if you have a member declared before you use public, private, or protected, it defaults to public in a struct and private in a class.

Otherwise, there's absolutely no functional difference between a struct and a class.

Typically, you use a struct when you have something that's intended to be POD (plain-old data) or to clearly indicate that all its members are public (or even that it has no members). You could just as easily use a class and just declare everything public, but using struct is often clearer and requires less typing.
 
another common use of struct is to define an interface.
Code:
struct car{
  virtual float getTopspeed()=0;
  virtual int getdoors()=0;
  virtual int getHorsepower()=0;
};

-pete
 
struct {
...
};

is the same as

class {
public:
...
};

I normally use struct if the code has to work in C as well and class if it is purely C++.

However, if you are working on a site which uses C# as well, be careful: in C#, struct is created on the stack, class is created on the heap.
 
One side note

struct
{
int a,b,c;
constructor
destructor
functions
};

class
{

constructor
destructor
functions
...
int a,b,c;
}

sizeof(struct) will be the sizeof the datamembers but the sizeof(class) may not. Useful when you want to dump the struct to a file and read it back in (in the no class or pointer situtation).

Matt
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top