Skip to main content
gamedev.net
🔒 Locked

c/c++ structs and pointers question

Started by voidless 7 replies 1.4k views
Original Post
voidless
voidless
if i have the following struct: struct x{ int a; int b; }; and in the main() we have: struct x* k; i know i can access a member of k via (*k).a or k->a but i always wondered if both works the same way, or one is different from the other? and if why, and which one is more optimal? thank you
stonemetal
stonemetal
-> is what is known as syntactic sugar. Something that makes your code look nice but adds no value or power to the language.
DevFred
DevFred
Quote:
Original post by voidless
struct x* k;

In C, the struct keyword is required here, but you don't need it in C++. Just write
x* k;

Of course, there is no such language as C/C++, but I assume you mean C++ when you say C/C++.
Black Knight
Black Knight
Also in C++ struct behaves exactly like a class, the only difference is the members of a struct are public whereas class members default to private.Well thats what I know anyways [smile]

struct Foo
{
int x;
int y;
};

x and y are public.

class Bar
{
int x;
int y;
};

x and y are private.

Am I correct ?
Aardvajk
Aardvajk
Quote:
Original post by Black Knight
Am I correct ?


Yes.

Also, inheritance is public by default for structs and private by default for classes.
ToohrVyk
ToohrVyk
Black Knight:

Quote:
The Most Holy C++ Standard, psalm 9.4 (Blessed Be Its Subsections)
A structure is a class defined with the class-key struct; its members and base classes (clause class.derived) are public by default (clause class.access). A union is a class defined with the class-key union; its members are public by default and it holds only one data member at a time (class.union).
voidless
voidless
thanks for the replies
hamo26
hamo26
Historically, A struct is actually the pioneer for it was developed before classes. As some people said a struct is usefull for simple objects if you want to avoid that complicated class decleration (lol).

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.