-4

I am working on OOPs and using C++. I have one class accessing object of other class/struct.

struct data
{
   int a;
   int b;
   string str;
} sd;

class format 
{
   int x;
   void show()
   {
      cout << data.a << endl;         
   }      
};

which one is best to use here class or struct?

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Manish
  • 3,341
  • 15
  • 52
  • 87
  • 1
    you can't access `data.a` in `format::show()`, `data` is a type – billz Mar 21 '14 at 08:43
  • 2
    No such thing as `strut`, it's `struct`. This code does not even compile. You can also _your-favorite-search-engige_ it. And there are a lot of questions like this one here. – Kiril Kirov Mar 21 '14 at 08:43
  • 1
    It is purely down to convention, there is no real technical difference (you can express the same types using either `class` or `struct`.) – juanchopanza Mar 21 '14 at 08:46
  • Related: http://stackoverflow.com/questions/92859/what-are-the-differences-between-struct-and-class-in-c – juanchopanza Mar 21 '14 at 08:48

3 Answers3

1

First of all, it's struct, not strut.

Second, you cannot access member a like you do, data.a, but rather sd.a, because you need to access it on an instance, not on the name of the struct.

For the detailed differences between class and struct see this SO question and its two best rated answers.

Community
  • 1
  • 1
nestedloop
  • 2,596
  • 23
  • 34
1

I use this convention:

  • A struct only have members that it make sense to manipulate directly
  • A class may have complicated rules for assigning members

This somewhat fits well with the default accessibility rules. But as said before in this thread, the choice depends on convention.

user877329
  • 6,717
  • 8
  • 46
  • 88
0

that depends on your requirement the only difference in struct and class is in struct all members are public by default and private in case of class

nikhil mehta
  • 972
  • 15
  • 30