I have forgotten
my Password

Or login with:

  • Facebookhttp://facebook.com/
  • Googlehttps://www.google.com/accounts/o8/id
  • Yahoohttps://me.yahoo.com
Index » Programming » Tutorials » C & C++ » Basic »

struct versus class

CodeCogs\′s Photo
3 Dec 07, 8:43AM
struct versus class
Classes (class) and Structures (struct) are absolutely identical except that all members of a class are private by default, while all members of a struct are public by default.

In other words, if you create a class, e.g.
class AClass
{
  int a;
  double d;
};
Then the only way the variables a or d can be adjusted is by other member functions of AClass, i.e.
class AClass
{
  int a;      // This is private data
  double d;   // This is private data
 
public:
  set_a(int val) {    // This is a public function
    a=val;
  }
 
  set_d(double val) {  // This is a public function
    d=val;
  }
}
 
int main()
{
  AClass A;
  A.a=10;      // *** This is illegal
  A.b=3.14;    // *** This is illegal
  A.set_a(10);
  A.set_d(3.141);
  return 0;
}
Within this clas you see a basic example of C++ encapsulation, where the internal data within the class is hidden and can only be controlled only by some carefully defined interface functions, i.e. set_a(..) and set_d(..). These function can perform all sorts of error checking, and so long as the interface is retained, we can change the way the data is stored as often as we like without breaking the rest of the program.

Conversely, the default content of a struct can be adjusted by anyone, e.g.
struct AStruct
{
  int a;
  double d;
};
 
int main()
{
  AStruct A;
  A.a=10;
  A.d=3.14;
 
  return 0;
}

Structures without member functions were a core element of C. Classes only exist in C++. As a result many developers often continue to use struct to create basic data containers, without member functions, while they use class in all other scenarios. Thought strictly a class or struct can be made to perform as the other simply by inserting the appropriate scope override. For example, to make a class perform as a structure add public:, i.e.

class A 
{
public:
  int a;
};

And to make a structure perform as a class, add private:, i.e.
struct A
{
private:
  int a;
};

Currently you need to be logged in to leave a message.