Archived

This topic is now archived and is closed to further replies.

i8degrees

quick question - relation with classes and structs?

Recommended Posts

i8degrees    122
hey, i''ve just started reading about C++ and OOP, i''m wondering... typedef struct filing_data // the class { char fname[30]; char lname[30]; char phone_num[10]; } names; names list[4]; // the objects is that correct? would the structure really represent a class, because a strcuture DOES describe the valid data that you can put into each object... then the next piece of code, declares 4 instances of the class (the objects), which i can then use accordingly... now i''m sure classes have many advantages over structures, i just haven''t gotten that far in the book yet the book i''m reading is C++ Primer Plus by Stephen Prata, i like it so far. thanks, bye.

Share this post


Link to post
Share on other sites
sjelkjd    171
The syntax you provided is C code. The typedef is there because C requires you to prefix all your structs with "struct" when you use them.

A class, as used in c++, usually refers to an object that has data and functions that work on that data.

Share this post


Link to post
Share on other sites
supergeek2k    122

  
struct filing_data
{
char fname[30];
char lname[30];
char phone_num[10];
};


is the same thing as

  
class filing_data
{
public:
char fname[30];
char lname[30];
char phone_num[10];
};


If I am not mistaken, the only difference between the 2 in C++ is that members of a struct default to public while members of a class default to private.

Peace,
Geek

Share this post


Link to post
Share on other sites
Oluseyi    2103
quote:
Original post by sjelkjd
The typedef is there because C requires you to prefix all your structs with "struct" when you use them.

No, it doesn''t. It''s just that if you don''t typedef it, then you have to use struct Structname whenever you want to declare an instance:

// C code
struct Vector2
{
long x;
long y;
};
Vector2 v; // illegal
struct Vector2 v2; // legal

I don''t know if that behavior has been changed in C99. This is why you see struct declarations like so:

typedef struct tagVector2
{
long x;
long y;
} Vector2;

Vector2 is a typedef for struct tagVector2, which is a legal statement by conventional C syntax.

In C++, structs are classes, with the sole differences that a) they default to public acces, and b) they default to public inheritance. Unions are also classes in C++.

[ GDNet Start Here | GDNet Search Tool | GDNet FAQ | MS RTFM [MSDN] | SGI STL Docs | Google! ]
Thanks to Kylotan for the idea!

Share this post


Link to post
Share on other sites