structure, class and union

invisible.hippo

Arch-Supremacy Member
Joined
Nov 8, 2008
Messages
17,902
Reaction score
315
Hi, i am learning class , structure and union

However i dont know how to apply it in practice. I do know that the members in a class are private and in structure are public.

E.g would be
Code:
// Program 1
#include <stdio.h>
 
class Test {
    int x; // x is private
};
int main()
{
  Test t;
  t.x = 20; // compiler error because x is private
  getchar();
  return 0;
}
// Program 2
#include <stdio.h>
 
struct Test {
    int x; // x is public
};
int main()
{
  Test t;
  t.x = 20; // works fine because x is public
  getchar();
  return 0;
}

However i dont know how to apply it in practice, like if i were to change the member in class to be public wouldnt it be same as a structure? If by doing so what would be the difference then?

Secondly, i come across that class can do overload(which i have no clue and still trying to read up more) which i believe structure does not have(i never come across overloading in structure).

I believe that all for the difference. I hope someone can
1) tell me is my understanding correct
2) hopefully show me the practical difference between class and structure ( more in dept)

i feel that most tutorial video/guide are too brief(they only explain, but did not really put into oop concept)
 

invisible.hippo

Arch-Supremacy Member
Joined
Nov 8, 2008
Messages
17,902
Reaction score
315
i have a assignment that is to combine union and structure together. I manage to research this ppt slide but i dont understand what does the code mean.
dpiq8k.jpg

for this example
struct - Switchcase statement issue. Reading info from txt file c++ - Stack Overflow

instead of doing this
Code:
  struct Local
    {
        char name[MAX];
        char nationality[MAX];
        char gender[MAX];
        Birthday bd;
        char subjects [MAX][MAX];
        char grades [MAX][MAX];
        int numOfCourses;

    };

    struct Foreigner
    {
        char name[MAX];
        char nationality[MAX];
        char gender[MAX];
        Birthday bd;
        char subjects [MAX][MAX];
        char grades [MAX][MAX];
        int numOfCourses;
    };

    union Student
    {
        Local     localStudent;
        Foreigner foreignStudent;
    };

After which why did the person go on to delcare a new strucutre for the enum and union ?

Code:
  struct UowStudents
    {
        CountryType ct;
        Student st;
    };



can i do as shown in ppt slide? what would be the difference
Code:
    union Student
    {
        Local     localStudent;
        Foreigner foreignStudent;
    }stud;


  struct Local
    {
        char name[MAX];
        char nationality[MAX];
        char gender[MAX];
        Birthday bd;
        char subjects [MAX][MAX];
        char grades [MAX][MAX];
        int numOfCourses;
       student stud;
    };

    struct Foreigner
    {
        char name[MAX];
        char nationality[MAX];
        char gender[MAX];
        Birthday bd;
        char subjects [MAX][MAX];
        char grades [MAX][MAX];
        int numOfCourses;
        student stud;
    };


one last thing, if i change to class, what will happen?
Code:
    union Student
    {
        Local     localStudent;
        Foreigner foreignStudent;
    }stud;


  struct Local
    {  
        public:
        char name[MAX];
        char nationality[MAX];
        char gender[MAX];
        Birthday bd;
        char subjects [MAX][MAX];
        char grades [MAX][MAX];
        int numOfCourses;
       student stud;
    };

    class Foreigner
    {
        public:
        char name[MAX];
        char nationality[MAX];
        char gender[MAX];
        Birthday bd;
        char subjects [MAX][MAX];
        char grades [MAX][MAX];
        int numOfCourses;
        student stud;
    };
 

invisible.hippo

Arch-Supremacy Member
Joined
Nov 8, 2008
Messages
17,902
Reaction score
315
i hope i am not bombarding....

Does union not work well in class or structure? why are they so many tutorial on union vs struct
union vs class, but not on union nested in struct?
 
Last edited:

davidktw

Arch-Supremacy Member
Joined
Apr 15, 2010
Messages
13,550
Reaction score
1,302
Hi, i am learning class , structure and union

However i dont know how to apply it in practice. I do know that the members in a class are private and in structure are public.

E.g would be
Code:
// Program 1
#include <stdio.h>
 
class Test {
    int x; // x is private
};
int main()
{
  Test t;
  t.x = 20; // compiler error because x is private
  getchar();
  return 0;
}
// Program 2
#include <stdio.h>
 
struct Test {
    int x; // x is public
};
int main()
{
  Test t;
  t.x = 20; // works fine because x is public
  getchar();
  return 0;
}

However i dont know how to apply it in practice, like if i were to change the member in class to be public wouldnt it be same as a structure? If by doing so what would be the difference then?

Secondly, i come across that class can do overload(which i have no clue and still trying to read up more) which i believe structure does not have(i never come across overloading in structure).

I believe that all for the difference. I hope someone can
1) tell me is my understanding correct
2) hopefully show me the practical difference between class and structure ( more in dept)

i feel that most tutorial video/guide are too brief(they only explain, but did not really put into oop concept)
https://www.hscripts.com/tutorials/cpp/structures-unions.php
Structure vs class in C++ - GeeksforGeeks

Structure is a spill over construct from the language C. C++ extended it into classes to include functional members and decided that structures members by default are have public visibility and classes have private visibility.

Fundamentally they are pretty much interchangeable as long as you are aware of the nuances in them. However from a OOP perspective, you are recommended to stick with the use of Class for consistent references to object oriented context given a choice. Not all programming languages uses class to define a class entity, but right here in C++, you have the option of using Class, so stick with it.

Leave structure for purely data constructs. However given that C++ is a OOP, there is much less value to stick with the older usage of structures for data encapsulation since the concept of a class play this role.

There are a lot more about OOP than just having members in a construct. These include polymorphism, inheritance, methods overwriting, methods overloading, accessors so forth. C++ among other OOPL has even more complicated constructs such as methods being virtual or not to allow or disallow overwriting, operators overloading etc.

Are you actually learning from a C++ book ? If so, these topics are explained in succession and well explained.

Unions is also a construct from the C days.

Unions are overlapping concept of reusing the same memory allocation for different purpose.

Code:
union U {
  int a;
  char b[4];
}

If I declare a union as such

union U u;

I can do this

u.a = 123;
printf("%s", b);

However you wouldn't see "123". That is because the binary representation of integer 123 is not the same as the binary representation of characters "123". You will probably see some gibberish characters.

The usage of unions can actually implement a form of OOPL concept called polymorphism and you can find it extensively used in the opensource GTK toolkit. The developers made use of structures and unions and macros with identifier to identify the type of the data type and then react as accordingly.

Code:
union U {
  int type;
  char* type_A_data;
  int type_B_data;
  float type_C_data;
}

This concept are used in loosely typed scripting languages such as perl, php, ruby and others for the dynamic typing system to understand what each variable is in the memory and hence can easily transform from one to another when the operations demands it

For example, using PHP,

$a = 1;
$b = 3;

print $a + $b, "\n";
print $a.$b, "\n";

Variables of these loose typing can be implemented using unions of the following form

Code:
struct Integer ...;
struct Float ...;
struct String ...;

struct VariableType {
  int data_type;
  union {
	struct Integer i;
	struct Float f;
	struct String s;
  } data;
} v;

Depending on the data_type value, you can access accordingly v.data.i, or v.data.f with all occupying the same memory block unit.
 
Last edited:

invisible.hippo

Arch-Supremacy Member
Joined
Nov 8, 2008
Messages
17,902
Reaction score
315
hi david, do you mind helping me with my doubts for practical, i have post them im 2nd post. Can you help to explain/correct them?
 

invisible.hippo

Arch-Supremacy Member
Joined
Nov 8, 2008
Messages
17,902
Reaction score
315
in this webpage Struct, Union and Class « C++ Home

How does the way the union work together with the structure?

Code:
struct {
float savings;
float checking;
float mortgage;
float interest;
float fees;
} BankStatement;


union {
short month;
short day;
int year;
} DATE;


typedef struct {
int hour;
int min;
int sec;
char AmPm;
} TIME;


A struct can also have a struct object as a member variable.
typedef struct {
bool deposit;
bool withdraw;
float Amount;
float newBalance;
DATE date;
TIME time;
} Transaction;
 
Last edited:

davidktw

Arch-Supremacy Member
Joined
Apr 15, 2010
Messages
13,550
Reaction score
1,302
hi david, do you mind helping me with my doubts for practical, i have post them im 2nd post. Can you help to explain/correct them?

Before I start answering more of your questions, are you reading how to program C++ from a book ?
 

davidktw

Arch-Supremacy Member
Joined
Apr 15, 2010
Messages
13,550
Reaction score
1,302
no, i reading bits and pieces from online tutorial and video from youtube.

Please stop doing this. Go and get yourself a proper C++ book and learn. You are going to confuse yourself doing this. This is not the proper way to learn something. You are not at the level of picking up a new topic in such manner until you have a mature and solid foundation on programming languages.

Even the same terminology behaves differently between different programming languages. Learn proper C++ programming from top down. Do not nitpick on topics when learning it.

There are much more difficult topics largely related to C++, namely the STL that can confuse you even much more than the features of C++.

There is no point for me to further explain to you on structures and unions until you have picked up the foundation of programming in C++ properly. These topics are explained properly in C++ programming books and you should be able to grasp them as you proceed.
 

Bonadaly

Arch-Supremacy Member
Joined
Aug 10, 2008
Messages
18,685
Reaction score
0
Please stop doing this. Go and get yourself a proper C++ book and learn. You are going to confuse yourself doing this. This is not the proper way to learn something. You are not at the level of picking up a new topic in such manner until you have a mature and solid foundation on programming languages.

Even the same terminology behaves differently between different programming languages. Learn proper C++ programming from top down. Do not nitpick on topics when learning it.

There are much more difficult topics largely related to C++, namely the STL that can confuse you even much more than the features of C++.

There is no point for me to further explain to you on structures and unions until you have picked up the foundation of programming in C++ properly. These topics are explained properly in C++ programming books and you should be able to grasp them as you proceed.

Is the book from C++ creator good for learning C++?
 

davidktw

Arch-Supremacy Member
Joined
Apr 15, 2010
Messages
13,550
Reaction score
1,302
Is the book from C++ creator good for learning C++?

I have mentioned before, the "good" of a book is subjective to individual. One should go and flip the book and find out if the way the author wrote is something you can easily grasp.

I normally go for Wrox or O'reilly kind of books, but it doesn't always has to be the case too.
 

KnightNiwrem

Senior Member
Joined
Jun 1, 2014
Messages
1,057
Reaction score
0
I have mentioned before, the "good" of a book is subjective to individual. One should go and flip the book and find out if the way the author wrote is something you can easily grasp.

I normally go for Wrox or O'reilly kind of books, but it doesn't always has to be the case too.

Indeed. How one learns best varies from individual to individual. Some learns better reading it visually, others prefer an audio explanation.

I believe I've directed invisible hippo to view some Good University C++ intro lectures, tutorials and assignments. At least, Universities have much better experience in teaching these topics in a pedagogically sound manner.

If he has diverged into random online tutorial by less-experienced individuals, though, I will be SAD! :(
 

Bonadaly

Arch-Supremacy Member
Joined
Aug 10, 2008
Messages
18,685
Reaction score
0
Indeed. How one learns best varies from individual to individual. Some learns better reading it visually, others prefer an audio explanation.

I believe I've directed invisible hippo to view some Good University C++ intro lectures, tutorials and assignments. At least, Universities have much better experience in teaching these topics in a pedagogically sound manner.

If he has diverged into random online tutorial by less-experienced individuals, though, I will be SAD! :(

What links? SIC :(
 

davidktw

Arch-Supremacy Member
Joined
Apr 15, 2010
Messages
13,550
Reaction score
1,302
Indeed. How one learns best varies from individual to individual. Some learns better reading it visually, others prefer an audio explanation.

I believe I've directed invisible hippo to view some Good University C++ intro lectures, tutorials and assignments. At least, Universities have much better experience in teaching these topics in a pedagogically sound manner.

If he has diverged into random online tutorial by less-experienced individuals, though, I will be SAD! :(

Looking at the university handouts, I wouldn't consider them as comprehensive sources of information for acquiring the knowledge of programming for starters. Reason is there are some of the knowledge passed down via lectures from the lecturer directly in verbal form and not found in the handouts.

A book on the other hand is intended for reading purpose and hence the author will write down every piece of detail that he/she has intended to convey across to the audience. That doesn't mean the written form is the best approach, but at least it is complete on its own.

Reading the lecture handouts only consist of the written knowledge with the verbal portion missing. Normally slides are meant to be indicative, concise and not meant for comprehensiveness.
 

KnightNiwrem

Senior Member
Joined
Jun 1, 2014
Messages
1,057
Reaction score
0
Looking at the university handouts, I wouldn't consider them as comprehensive sources of information for acquiring the knowledge of programming for starters. Reason is there are some of the knowledge passed down via lectures from the lecturer directly in verbal form and not found in the handouts.

A book on the other hand is intended for reading purpose and hence the author will write down every piece of detail that he/she has intended to convey across to the audience. That doesn't mean the written form is the best approach, but at least it is complete on its own.

Reading the lecture handouts only consist of the written knowledge with the verbal portion missing. Normally slides are meant to be indicative, concise and not meant for comprehensiveness.

I believe that is because nobody should even be trying to complete this module on lecture slides and handouts alone.

Of course, if you take out the lecture component, it would be incomplete. I'm not sure what the point is.
 

*Pickle*

Arch-Supremacy Member
Joined
Aug 18, 2014
Messages
19,117
Reaction score
5
I have mentioned before, the "good" of a book is subjective to individual. One should go and flip the book and find out if the way the author wrote is something you can easily grasp.

I normally go for Wrox or O'reilly kind of books, but it doesn't always has to be the case too.

I swear by O'reilly as well. The quality of the books they publish are mostly consistent and I have nothing but praises for the books I've read so far.
 

*Pickle*

Arch-Supremacy Member
Joined
Aug 18, 2014
Messages
19,117
Reaction score
5
I believe that is because nobody should even be trying to complete this module on lecture slides and handouts alone.

Of course, if you take out the lecture component, it would be incomplete. I'm not sure what the point is.

The point is, jump straight to books. Clear enough?
 

Bonadaly

Arch-Supremacy Member
Joined
Aug 10, 2008
Messages
18,685
Reaction score
0
Looking at the university handouts, I wouldn't consider them as comprehensive sources of information for acquiring the knowledge of programming for starters. Reason is there are some of the knowledge passed down via lectures from the lecturer directly in verbal form and not found in the handouts.

A book on the other hand is intended for reading purpose and hence the author will write down every piece of detail that he/she has intended to convey across to the audience. That doesn't mean the written form is the best approach, but at least it is complete on its own.

Reading the lecture handouts only consist of the written knowledge with the verbal portion missing. Normally slides are meant to be indicative, concise and not meant for comprehensiveness.

How about MOOCs???? :(
 
Important Forum Advisory Note
This forum is moderated by volunteer moderators who will react only to members' feedback on posts. Moderators are not employees or representatives of HWZ Forums. Forum members and moderators are responsible for their own posts. Please refer to our Community Guidelines and Standards and Terms and Conditions for more information.
Top