12 Replies - 10564 Views - Last Post: 12 May 2010 - 08:57 AM Rate Topic: -----

#1 masoug  Icon User is offline

  • D.I.C Head

Reputation: 22
  • View blog
  • Posts: 181
  • Joined: 30-December 09

What is the Difference Between Struct and Class?

Posted 09 May 2010 - 05:50 PM

Hi,
Between C and C++, what is the difference between Structures and Classes? Google said that they are nearly the same. Then why did Bjarne Strostrup (did I spell that correctly?) bother with C++?

THANKS!

-Masoug
Is This A Good Question/Topic? 0
  • +

Replies To: What is the Difference Between Struct and Class?

#2 Martyr2  Icon User is online

  • Programming Theoretician
  • member icon

Reputation: 4332
  • View blog
  • Posts: 12,127
  • Joined: 18-April 07

Re: What is the Difference Between Struct and Class?

Posted 09 May 2010 - 05:59 PM

It is all about where they are stored. Structs are value types and are stored on the "stack" and classes are reference types and are stored on the "heap". Think of the stack as a quick limited space memory location and the heap as a large holding area of memory. When do you use one or the other? If you are creating a rather large object that would be cumbersome to copy and have to pass around, then use the heap (by making it a class) and refer to the objects through pointers. If it is a small structure and isn't passed around much but need to quickly access, then use a structure.

Lets play the class/struct game!

1) Object such as a vehicle with the ability to drive, honk the horn, and multiple attributes like color, model, make and the properties to get/set these values. This would be a class.

2) An object for storing a color. This would be best served by a struct.

3) A person. Probably would be a class because there is a lot of info stored about a person... name, age, height, weight and lots of actions they can do.

4) An object describing a web site's total and daily hits. Probably a struct since all you really have is a few integers to keep a tally.

5) Object to represent a file. Most likely a class since there is quite a bit of info you can use to describe a file. Size, name, location and plus may have lots of functions to manipulate that file like read(), write(), copy() etc.


Generally if the object is going to contain a lot of data and actions, go with a class. I personally always suggest a class because you never know what you might need later. Your struct may need to be upgraded and thus will eventually become a class anyways.

Hope this helps! :)

This post has been edited by Martyr2: 09 May 2010 - 06:01 PM

Was This Post Helpful? 2
  • +
  • -

#3 Oler1s  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1395
  • View blog
  • Posts: 3,884
  • Joined: 04-June 09

Re: What is the Difference Between Struct and Class?

Posted 09 May 2010 - 06:18 PM

Martyr2, your post reflects a C# view on structs and classes. It does not apply to C++.

Quote

Between C and C++
Between C and C++? C has no support for the OO paradigm.

Quote

Google said that they are nearly the same.
Only within C++ itself.

C does not have any OO constructs. It also lacks everything else in C++ like RTTI, exceptions, templates, better type safety, the larger standard library, and with C++0x, auto variables, movable rvalues, etc.

In C++, the only difference between classes and structs is that structs assume public while classes assume private access. For both members and inheritance from a base class.
Was This Post Helpful? 2
  • +
  • -

#4 NickDMax  Icon User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2250
  • View blog
  • Posts: 9,245
  • Joined: 18-February 07

Re: What is the Difference Between Struct and Class?

Posted 09 May 2010 - 06:21 PM

Wow... I don't think I have ever seen Martyr2 be so off before.

There is very very little differnce between a struct and class in C++. struct is merely an alias for a class that defaults to public access.


i.e these two constructs are *exactly* the same:
struct MyStuct { 
    int x, y;
    MyStruct(int x, int y) : x(x), y(y) { }
};

class MyClass {
public:
    int x, y;
    MyClass (int x, int y) : x(x), y(y) { }
};


Structs can have constructors, deconstructors, they can have virtual members, they can inherit from classes, they can have public, private, protected members -- the ONLY difference is the class members are private by default, and struct members are public by default.

Sorry Martyr2 you are not a struct vs. class ninja today :donatello:
Was This Post Helpful? 1
  • +
  • -

#5 NickDMax  Icon User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2250
  • View blog
  • Posts: 9,245
  • Joined: 18-February 07

Re: What is the Difference Between Struct and Class?

Posted 09 May 2010 - 06:28 PM

Quote

why did Bjarne Strostrup (did I spell that correctly?) bother with C++?
-- A struct in C++ and a struct in C are NOT the same thing... they are close, but not the same. In C a struct can not have member functions, in C++ a struct CAN have member functions... In C++ a struct is a type of class and can be used for Object Oriented Programming (OOP) but in C there is not proper OOP.

In review:

C++ class vs C++ struct -- same thing different default access modifier.

C++ struct vs C struct -- upwardly compatible, a C struct works just fine in C++, but C++ adds features that are not in C. For example a C++ struct can contain code.


It IS interesting that they are so close... turns out that they are closer than you might think, every C++ program can be compiled into a C progrom. All OOP really is, is a set of rules, you can use OOP programming in non-OOP languages but you have to enforce the rules yourself. OOP languages are much more structured and the language itself enforces the rules for you.
Was This Post Helpful? 1
  • +
  • -

#6 jjl  Icon User is offline

  • Engineer
  • member icon

Reputation: 1072
  • View blog
  • Posts: 4,532
  • Joined: 09-June 09

Re: What is the Difference Between Struct and Class?

Posted 09 May 2010 - 06:39 PM

in C++ structs and class are the same, the only difference is that structs are default public and classes are default private. Typically structs are used for containers for variables while classes usually include methods and functions and all that jazz. But again that is just based on programming style, you can choose to use them anyway you want
Was This Post Helpful? 0
  • +
  • -

#7 Martyr2  Icon User is online

  • Programming Theoretician
  • member icon

Reputation: 4332
  • View blog
  • Posts: 12,127
  • Joined: 18-April 07

Re: What is the Difference Between Struct and Class?

Posted 11 May 2010 - 08:00 PM

First of all, my view does not just reflect C#, I read it correctly the first time. There is a difference between structs and classes and where they are "generally" located. I use the term generally because you can indeed bend the rule. However it is not advised unless you have a wickedly small class that should probably be a struct. When you use a class, you typically use the "new" keyword to instantiate it. This pulls HEAP memory. Structs on the other hand are typically defined on their own and are thus are placed on the stack, just like int, float, boolean etc.

Can you place a class on the stack? Sure. Do you want to 100% of the time? NO! I was not commenting on C having classes or not, I was addressing what is the difference between a class and a struct in C++. And if you people think how they are used is virtually equivalent and placing your heavy objects on the stack, boy, you really need to review your program's performance. C# just expanded on this philosophy and which is why it did create the value type/reference type and introduced garbage collection.

Next because a class is generally carrying around methods and tend to be bigger, this is the reason we have pointers. We do not want to be passing around objects without pointers in C++. Can you without pointers? Again yes, but it is bad practice and bad design to do so. Without pointers, we would be copying objects which again is a horrible deal.

:rolleyes2:

This post has been edited by Martyr2: 11 May 2010 - 08:02 PM

Was This Post Helpful? 0
  • +
  • -

#8 jjl  Icon User is offline

  • Engineer
  • member icon

Reputation: 1072
  • View blog
  • Posts: 4,532
  • Joined: 09-June 09

Re: What is the Difference Between Struct and Class?

Posted 11 May 2010 - 08:22 PM

Quote

When you use a class, you typically use the "new" keyword to instantiate it. This pulls HEAP memory. Structs on the other hand are typically defined on their own and are thus are placed on the stack, just like int, float, boolean etc.


That just sounds like personal preference. I feel that memory should only be allocated on the heap if it is necessary for the memory to be dynamic. If its known memory there not reason not to allocate it to the stack
Was This Post Helpful? 1
  • +
  • -

#9 Oler1s  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1395
  • View blog
  • Posts: 3,884
  • Joined: 04-June 09

Re: What is the Difference Between Struct and Class?

Posted 11 May 2010 - 09:01 PM

Quote

There is a difference between structs and classes and where they are "generally" located.
There is not. There is no "general" location. You need to look at the actual standard. Look at the latest drafts which are available online. Look at the section on classes. It's section 9 in the N3090 draft (I think). Please look, because the section explicitly tells you that class and struct are considered a "class-key" token. And section 11 (Member access control) tells you that with class, members are private by default, and with struct, members are public by default.

Quote

When you use a class, you typically use the "new" keyword to instantiate it.
Really? Ever write something like std::string myString? That's an object (of type std::string) on the stack. Or are you saying your code always looks like std::string * myStringP; everywhere (or the smart pointer equivalent)?

Quote

placing your heavy objects on the stack, boy, you really need to review your program's performance.
Umm..you understand that heavy objects are placed in the heap because stack size is limited, right? Or that the size required is not known until runtime. Stack size requirements need to be determinate at compile time. In fact, storing on the heap is expensive. Every call to new is at best minimally expensive (in a well designed allocator), and at worst, gets you a penalty, where the allocator must acquire additional space from the OS and do additional bookkeeping.

Acquiring from the heap is a penalty. When you design types that need to manage large resources, your types should use handles to that resource, as opposed to reserving space on the stack. Which of course is not a concern if resource size is not even known at compile time. But it's a penalty nonetheless.

Quote

Next because a class is generally carrying around methods and tend to be bigger, this is the reason we have pointers.
A class carrying around methods? You understand that member functions are basically like free functions with a hidden parameter, the hidden parameter being the identification of the object? Execute the following code and see for yourself:

#include <iostream>

class A
{
	int a;
	int b;
	int c;
};

class B
{
	int a;
	int b;
	int c;
public:
	void doSomething()
	{
		c = a + b;
	}
};

int main()
{
    A a;
    std::cout << sizeof(A) << ',' << sizeof(B)/> << '\n';
}



If you want, I can also pull out elements from the standard (or, you can read the standard yourself), that indicate that functions do not increase class size.

Quote

Next because a class is generally carrying around methods and tend to be bigger, this is the reason we have pointers.
I have thrown out your first statement, but the second is even more shocking. Pointers are carried over from C, where classes do not exist. Thus indicating that pointers exist because of classes is a contradiction. Pointers exist because they implement referential semantics. A good example of where such semantics is critical is in a linked list. There is no other syntactical construct that indicates a handle to another object. C++ references instead indicate another semantic, which is that of aliases.

Martyr2, your entire post is inexplicable. There is absolutely no way you can reach these conclusions based on a reading of any proper C++ text and the standard throughly contradicts you. Furthermore, your statements are disproved by code like above.

This post has been edited by Oler1s: 11 May 2010 - 09:02 PM

Was This Post Helpful? 2
  • +
  • -

#10 Martyr2  Icon User is online

  • Programming Theoretician
  • member icon

Reputation: 4332
  • View blog
  • Posts: 12,127
  • Joined: 18-April 07

Re: What is the Difference Between Struct and Class?

Posted 11 May 2010 - 11:35 PM

Quote

And section 11 (Member access control) tells you that with class, members are private by default, and with struct, members are public by default.


Never did I argue this fact.


Quote

Really? Ever write something like std::string myString? That's an object (of type std::string) on the stack. Or are you saying your code always looks like std::string * myStringP; everywhere (or the smart pointer equivalent)?


What part of typically do you not understand? Again I said that in the majority of cases, specially when the object is a heavy object you should be using a pointer to it. End of story dude. Any time you declare a "heavy" object and not reference it using a pointer and then pass it around to functions you are recopying it. Again, not an issue if the class is small, but in most situations either a class is heavier than a struct or may eventually be modified to become heavier.

Quote

Umm..you understand that heavy objects are placed in the heap because stack size is limited, right?


Hence the reason you should limit what you do put on the stack. The stack is no place for heavy objects. There is a reason we have a heap.

Quote

Acquiring from the heap is a penalty.


Of course it is going to cost, but its savings over moving around large objects and making unnecessary copies will be greatly realized. I don't know why you seem to be against initiating a class on the heap with a new keyword and a pointer. That is C++ memory management at its best. This is a GOOD thing.

Quote

A class carrying around methods? You understand that member functions are basically like free functions with a hidden parameter, the hidden parameter being the identification of the object?


Yes a class carries around methods with it. It wraps up functions. You know, the reason we call them methods instead of functions. And when I say they are bigger I am saying that your typical function isn't just going to add 2 + 2, instead they will declare their own variables, make other calls, and consume their own resources.

OBJECTS ARE CONSIDERED HEAVY COMPARED TO STRUCTS! Again, another reason why in C# they end up making a clear distinction between what is a value type and what is a reference type. This came from C++ and the direction it was going.

I am not here to argue the finer details of C++ internals. I was answering the original posters question about structs and classes. I think you just took something personally and think I am out attacking everything you are saying. You claimed I was talking from a C# stand point and while my statements do act similar in C#, the ideas in C# when it comes to structs and classes has its roots in the very fact that structs are considered lighter than classes.

So chill out and be merry. ;)

This post has been edited by Martyr2: 11 May 2010 - 11:37 PM

Was This Post Helpful? 1
  • +
  • -

#11 Anarion  Icon User is offline

  • The Persian Coder
  • member icon

Reputation: 282
  • View blog
  • Posts: 1,456
  • Joined: 16-May 09

Re: What is the Difference Between Struct and Class?

Posted 12 May 2010 - 01:45 AM

There is no must to use pointers:

Quote

Any time you declare a "heavy" object and not reference it using a pointer and then pass it around to functions you are recopying it

From what I have learned till now, the copying happens when you pass objects by value. In C++, you don't Have to use pointers to avoid the copy when using pass by value, instead you can use references:

class heavy {
    //codes of heavy object
};

void test_function(heavy& heavy_object) {
    //...
}


In the above code, I could use a pointer in test_function's argument. But using a reference solves the copying problem and also, avoids using a pointer(which helps safety).

More Information About References

This post has been edited by Anarion: 12 May 2010 - 02:23 AM

Was This Post Helpful? 2
  • +
  • -

#12 jjl  Icon User is offline

  • Engineer
  • member icon

Reputation: 1072
  • View blog
  • Posts: 4,532
  • Joined: 09-June 09

Re: What is the Difference Between Struct and Class?

Posted 12 May 2010 - 08:47 AM

Quote

When you use a class, you typically use the "new" keyword to instantiate it.

Quote

Again I said that in the majority of cases, specially when the object is a heavy object you should be using a pointer to it. End of story dude. Any time you declare a "heavy" object and not reference it using a pointer and then pass it around to functions you are recopying it.



you are aware that you are allowed to have a pointer pointing to memory located on the stack right. Just because something is a pointer doesnt mean it has to be allocated on the heap.

class Heavy
{
/*some stuff*/
};

void passObject(Heavy *passObject)
{

}

int main()
{
    Heavy myObject;
    passObject(&myObject);



there is no requirement that "classes" must be dynamically allocated, either that say that structs must be allocated on the stack.

Quote

And when I say they [classes] are bigger I am saying that your typical function isn't just going to add 2 + 2, instead they will declare their own variables, make other calls, and consume their own resources.

which one you thinks bigger?

class Heavy
{
	int a;
	public:
	void declare(void)
	{
	int b,c,d,e,f,g,h,i,j,k,l;
	}

};

class Lite
{
	int a;
        public:
	void declare(void)
	{
	}
};

int main()
{
	Heavy h_obj;
	Lite l_obj;
	if(sizeof(h_obj) == sizeof(l_obj))
		cout<<"THERE THE SAME SIZE"<<endl;
		
		
	return 0;
}
		



This post has been edited by ImaSexy: 12 May 2010 - 09:00 AM

Was This Post Helpful? 0
  • +
  • -

#13 Oler1s  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1395
  • View blog
  • Posts: 3,884
  • Joined: 04-June 09

Re: What is the Difference Between Struct and Class?

Posted 12 May 2010 - 08:57 AM

In response to Martyr2's post.

Quote

Never did I argue this fact. (About the default access specifier)
I know you didn't argue that fact. What I'm insisting is that this is the only difference between classes and structs. That is, section 9 indicates "struct" and "class" to both be a class-key token, as in section 9. That the difference comes from section 11, and again I'm repeating myself. So I was looking for you to do two things. 1) Acknowledge or provide evidence against the default access specifier point I made and 2) Indicate if there are other differences and where the standard talks about them.

Quote

What part of typically do you not understand?
I don't understand the part about what makes something fall into the typical case and not. So std::string is an exception? What about streams? An exception too? What about container classes? An exception too? What about the entire Boost libraries? Exception as well?

If you were writing code, how would identify a class as being one you could allocate on the stack vs on the heap? In fact, I have trouble understanding this. You talk about heavy objects. Why don't you write code that demonstrates a "heavy" class? Show me code.

Quote

I don't know why you seem to be against initiating a class on the heap with a new keyword and a pointer. That is C++ memory management at its best. This is a GOOD thing.
Actually, it's a bad thing. As opposed to having the compiler manage the lifetime, you must keep track of it. How do you make guarantees about lifetime? Who is responsible, etc. That's why C++ has smart pointers and the RAII idiom. You've no doubt encountered this when you read material by the gurus on C++. Rather than having naked pointers, you use smart pointers which implement RAII. RAII means taking advantage of constructors and destructors to present an object that automatically allocates and deallocates memory. Thus we have smart pointers like shared pointers that implement different semantics. This isn't some unique thing I invented myself. You know this from the C++ standard library and Boost, right?

Quote

Yes a class carries around methods with it. It wraps up functions. You know, the reason we call them methods instead of functions.
This is a syntactical convenience. You suggest that having member functions affects the class. Yet my above code proves evidence against. What say you about the above code? Or are you going to ignore the code I give as evidence?

Quote

And when I say they are bigger I am saying that your typical function isn't just going to add 2 + 2, instead they will declare their own variables, make other calls, and consume their own resources.
So..what? Any function can do this. Any function call takes up space on the stack. Why are class member functions singled out? In particular, structs can have member functions too. So if you argument were valid, then logically, it should apply to structs as well. So are member functions of structs different from those of classes?

Quote

OBJECTS ARE CONSIDERED HEAVY COMPARED TO STRUCTS!
Well, this makes no sense as an object is a variable of a certain type, while structs are a type. But what you meant to say is that class objects are heavy compared to struct objects. Show me code. Show me an idiomatic, properly written class that is "heavy".

Quote

This came from C++ and the direction it was going.
That notion does not exist in C++.

Quote

I am not here to argue the finer details of C++ internals.
Neither am I. I am here to oppose your very wrong statements about structs and classes in C++. Both NickDMax and I oppose what you say. Google brings up people claiming the same. To make my arguments, I refer to the standard. I'm not being pedantic, but what you say is fundamentally wrong, not pedantically wrong.

Quote

I think you just took something personally and think I am out attacking everything you are saying.
I haven't taken anything personally. I consider you to have made wrong statements. I am attacking those statements.

Quote

very fact that structs are considered lighter than classes
You claim it's a fact. I am asking you to back it up. I am pointing to the standard (the N3090 draft in this case) to show that the standard considers them equivalent save for the default access specifier. Thus, your argument needs to fall into one of two patterns. You can either claim that the access specifier is what makes a type "heavy". Or you can claim that there is another aspect that makes them heavy. I am asking you to point out what that is. Demonstrate by writing code.

Literally, write code. You want to claim something about C++ that others disagree with? Show code or point to standard.

This post has been edited by Oler1s: 12 May 2010 - 08:59 AM

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1