473,769 Members | 2,100 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

difference between a structure and a class

I have been programming in C++ for over 4 years. I *think* I knew that
a struct could have a constructor but I decided to dig into it a little
more today, and found that there is very little difference between a
struct and a class in C++. Both have inheritance, access modifiers,
etc. The only diff I see is the default access level is public vs.
private.

I have always just used structs as a minimal class, as that is the way
they were used in textbooks.

Do structs have all these features in pure C? If not then why did c++
change them, when they were adding the Class type? Are there more
differences than those I have listed? Performance differences? I have
always just used structs as a minimal class, as that is the way they
were used in textbooks.

Thoughts, Ideas?

~S
Jul 23 '05 #1
11 5721

"Shea Martin" <sa************ **@hotmail.com> wrote in message
news:h1******** ************@ur sa-nb00s0.nbnet.nb .ca...
I have been programming in C++ for over 4 years. I *think* I knew that
a struct could have a constructor but I decided to dig into it a little
more today, and found that there is very little difference between a
struct and a class in C++. Both have inheritance, access modifiers,
etc. The only diff I see is the default access level is public vs.
private.
That is indeed the only difference. Note that also included
in 'access' is the default inheritance: class has 'private',
and struct has 'public'. That's why you'll typicall see
derived classes declared as:

class B : public A
I have always just used structs as a minimal class, as that is the way
they were used in textbooks.
Anything that can be done with a class can also be
done with a struct.

Do structs have all these features in pure C?
No.

If not then why did c++
change them,
Because C++ is not C.
when they were adding the Class type?
'class' is not a type. 'class' (and 'struct') is a keyword
the programmer can use to create custom (aggregate) types.

Are there more
differences than those I have listed?
No.
Performance differences?
That's an implementation detail not addresses by the
language. See "Quality of Implementation" .
I have
always just used structs as a minimal class, as that is the way they
were used in textbooks.
Objects created from a 'struct' definition are no
less than those created from a 'class' definition,
so 'minimal' does not apply.
Thoughts, Ideas?


Since the 'mechanics' are the same, I suggest using
the different keywords 'class' and 'struct' as
indicators of your intentions: I.e. use 'class'
when you're creating abstract types with special
functionality (e.g. polymorphism), use 'struct'
if simply grouping related simple data items (e.g.
a pair of integer objects). But ultimately, the
choice is yours (or often that of your employer/
client).
-Mike
Jul 23 '05 #2
"Shea Martin" <sa************ **@hotmail.com> wrote in message
news:h1******** ************@ur sa-nb00s0.nbnet.nb .ca
I have been programming in C++ for over 4 years. I *think* I knew
that a struct could have a constructor but I decided to dig into it a
little more today, and found that there is very little difference
between a struct and a class in C++. Both have inheritance, access
modifiers, etc. The only diff I see is the default access level is
public vs. private.

I have always just used structs as a minimal class, as that is the way
they were used in textbooks.

Do structs have all these features in pure C?
No. They don't have any of those features. Structs in C are just containers
for data types.
If not then why did c++ change them, when they were adding the Class type?
I suppose you would have to ask Stroustrup (or read his books), but you can
use structs exactly as they are used in C or you can use them with the added
features. Your choice. Isn't that better that only being able to use them as
in C?
Are there more
differences than those I have listed? Performance differences? I have
always just used structs as a minimal class, as that is the way they
were used in textbooks.


Default inheritance, in addition to access, is public with structs. I think
that is about all the differences, but maybe there is one more.
--
John Carson

Jul 23 '05 #3
On Fri, 03 Jun 2005 16:03:44 +0000, Mike Wahler wrote:
"Shea Martin" <sa************ **@hotmail.com> wrote in message
news:h1******** ************@ur sa-nb00s0.nbnet.nb .ca...
I have been programming in C++ for over 4 years. I *think* I knew that
a struct could have a constructor but I decided to dig into it a little
more today, and found that there is very little difference between a
struct and a class in C++. Both have inheritance, access modifiers,
etc. The only diff I see is the default access level is public vs.
private.
That is indeed the only difference. Note that also included
in 'access' is the default inheritance: class has 'private',
and struct has 'public'. That's why you'll typicall see
derived classes declared as:

class B : public A

[...] Since the 'mechanics' are the same, I suggest using
the different keywords 'class' and 'struct' as
indicators of your intentions:

[...]

Or better yet, to avoid putting tons of `public' in your code, you can
just use `struct' instead when you declare classes. Many (most?)
people seem to put public data members/functions at the top of their
class (and private at the bottom); the default access specifiers for
`class' are inconvenient for this style of layout (both for reading and
for writing).

class B : public A, public N, public Q<B> {
public:
void f();
};

vs.

struct B : A, N, Q<B> {
void f();
};

--
Jordan DeLong
fr******@allusi on.net

Jul 23 '05 #4

"John Carson" <jc************ ****@netspace.n et.au> wrote in message
news:d7******** **@otis.netspac e.net.au...
Default inheritance, in addition to access, is public with structs. I
think that is about all the differences, but maybe there is one more.


Yup -- different spelling. :-)

-Mike
Jul 23 '05 #5

"Shea Martin" <sa************ **@hotmail.com> wrote in message
news:h1******** ************@ur sa-nb00s0.nbnet.nb .ca...
I have been programming in C++ for over 4 years. I *think* I knew that
a struct could have a constructor but I decided to dig into it a little
more today, and found that there is very little difference between a
struct and a class in C++. Both have inheritance, access modifiers,
etc. The only diff I see is the default access level is public vs.
private.

A struct and a class is exactly the same thing (called an abstract type) so
long as we are confining the definition to the C++ language. The only
difference is the default access given to their members, ctors, dtor and
member functions.

Your statement about constructors is misleading, a class or struct *must*
have a constructor and a destructor, there is no choice offered here. The
question is: will the compiler generate defaults for you or did you choose
to provide the d~tor and ctors yourself? If you supply a single constructor
with arguement(s), for example, the compiler ceases to supply any default,
non-copy constructor. (see code below)

The compiler provides a default shallow copy-ctor and an assignment operator
as well. The compiler will always supply these until you overide the
compiler's responsability to do so. Again: same for struct and class.

I have always just used structs as a minimal class, as that is the way
they were used in textbooks.

Do structs have all these features in pure C? If not then why did c++
change them, when they were adding the Class type? Are there more
differences than those I have listed? Performance differences? I have
always just used structs as a minimal class, as that is the way they
were used in textbooks.


No difference at all between the two. One uses the keyword struct and the
other class. Even inheritence applies to both with respect for their access
defaults.

Note how the following Abstract class is not sufficient to create an array
of Abstract objects. An array requires a default constructor (thats the
law). The default constructor can't be supplied here because the compiler
acknowledges that the creator of the class has taken-over the responsability
to supply all non-copy constructors.

The following won't compile unless you uncomment the default ctor (or
comment-out all ctors for the compiler to generate them for you).

#include <iostream>

class Abstract
{
int a; // private
public:
// ctors
// Abstract() { std::cout << "default ctor invoked\n"; } // uncomment
this ctor
Abstract(int n) : a(n) { std::cout << "ctor invoked\n"; }
// d~tor
~Abstract() { std::cout << "\nd~tor invoked"; }
// copy-ctor
Abstract(const Abstract& r_copy)
{
std::cout << "copy-ctor invoked\n";
a = r_copy.getA();
}
// member function (accessor)
int getA() const { return a; }
};
int main()
{
Abstract array[5]; // an array of 5 default Abstract objects
Abstract abstract(99); // a single Abstract object with member a = 99
Abstract copy_of_abstrac t(abstract); // copy
array[0] = copy_of_abstrac t; // assignment

std::cout << "array[0].getA() = " << array[0].getA();

return 0;
}

Jul 23 '05 #6
Classes and structures also differ in terms of the memory
layout of member variables. In a simple structure,
the memory layout is in the order of the fields. In a class
the memory layout is undefined and compiler dependent.

--
EventStudio 2.5 - http://www.EventHelix.com/EventStudio
Auto Layout and Generate Sequence Diagrams in PDF and MS Word

Jul 23 '05 #7
"EventHelix.com " <ev********@gma il.com> wrote in message
news:11******** **************@ g44g2000cwa.goo glegroups.com
Classes and structures also differ in terms of the memory
layout of member variables. In a simple structure,
the memory layout is in the order of the fields. In a class
the memory layout is undefined and compiler dependent.


In circumstances in which a struct is guaranteed to have members laid out in
the order of declaration, an otherwise identical class will likewise have
members laid out in the order of declaration provided the class begins with
the keyword public:, as in

class X
{
public:
// stuff
};

In other words, the only difference is one of default access specifiers.
Adding public: changes the class's access and makes it equivalent to a
struct for layout purposes. If a struct has virtual members etc., then its
member layout is no longer guaranteed, just as with a class that has virtual
members etc.

--
John Carson

Jul 23 '05 #8
Shea Martin wrote:
Thoughts, Ideas?


Just a bit of trivia: A union can also have member functions (including
constructors and destructors) in C++. It cannot, however, participate in
inheritance or have virtual functions.

-Alan
Jul 23 '05 #9
"Alan Johnson" <al**@undisclos ed.com> wrote in message
news:d7******** **@news.Stanfor d.EDU
Shea Martin wrote:
Thoughts, Ideas?


Just a bit of trivia: A union can also have member functions
(including constructors and destructors) in C++.

True. However:

Section 9.5/1
"An object of a class with a non-trivial constructor (12.1), a non-trivial
copy constructor (12.8), a non-trivial destructor (12.4), or a non-trivial
copy assignment operator (13.5.3, 12.8) cannot be a member of a union, nor
can an array of such objects."

--
John Carson

Jul 23 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

22
3359
by: Ook | last post by:
We have had a discussion on the differences between a class and a structure, and no one is in agreement. As I understand it, a structure defaults to public, a class defaults to private. There are issues about constructors that I'm not clear on. I do know that I can take a simple project with a class that has constuctors, destructors, accessors, and modifiers, change the classes to structs, and it compiles and runs fine. Can some kind soul...
6
7671
by: nick | last post by:
I have tried finding an answer to this, but most people just explain classes as a more modular way to program. It seems to me that (forgetting OO programming which I don't quite understand) the structures in C are the same as classes in another language such as C++ or Java only missing the ability to make the data private. I've never had this explained sufficiently and would appreciate a good answer. It doesn't need to be Mickey Mouse,...
5
8732
by: Chris | last post by:
Hi, I don't get the difference between a struct and a class ! ok, I know that a struct is a value type, the other a reference type, I understand the technical differences between both, but conceptually speaking : when do I define something as 'struct' and when as 'class' ? for example : if I want to represent a 'Time' thing, containing : - data members : hours, mins, secs
6
77857
by: Ashish Sheth | last post by:
Hi All, In C#, How can I get the difference between two dates in number of months? I tried to use the Substract method of the DateTime class and it is giving me the difference in TimeSpan,From which I can get the duration in days, hours and so.. but how can I get the difference in months? Please reply ASAP. it's urgent. -- regards, Ashish Sheth
2
2325
by: SpotNet | last post by:
Hello NewsGroup, More out of curiosity, now I'd love to know which is a better way, if one can think in such terms in this context. If I implement the ChooseColor API function, the documentation states (briefly); BOOL ChooseColor(LPCHOOSECOLOR lpcc); lpcc is defined as "... Pointer to a CHOOSECOLOR structure that..." and you know or know where to read the rest of it.
7
12374
by: raghunandan_1081 | last post by:
Hi guys, can you please tell me what is the Difference between c structure and c++ structure
3
10499
by: AppleBag | last post by:
I'm new to the vb.net scene, (from vb6) and would appreciate if someone could explain the difference between the two? From all I've read they seem to be the exact same thing? And as an expansion of that question, if i declare a public arraylist, how do i view its items from any procedure I happen to be in (app-wide), in the locals window? thanks
4
1726
by: eBob.com | last post by:
In my class which contains the code for my worker thread I have ... Public MustInherit Class Base_Miner #Region " Delegates for accessing main UI form " Delegate Sub DelegAddProgressBar(ByVal uiform As Form1, ByRef si As MTCC02.Form1.SiteRunOpts, _ ByVal numitems As Integer) #End Region
9
3316
by: jinendrashankar | last post by:
Hi All, Can any one have any idea about this issue what is Difference between structure and class in C++ Other then by default structure have public scope and class have private scope For data member and member function .If there is no other difference between Class & structure then why we use 2 key world in C++ we can use either class or structure in C++ ?
0
10038
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9987
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9857
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8867
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7404
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5294
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3952
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3558
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2812
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.