-3

I'm new to programming and this is my first year of C++.

All I've understood is that structures are variables with many different data types... I was wondering if it is like a container of data types. Or is it just data? Or both?

For example :

struct data {

int    data_type_integer;
string data_type_string;
char   data_type_char;
float  data_type_float;
} variable1;

So in this case, the variable (variable1) contains 4 data types: (int, string, char, float)

But what if we have 2 of the same data types? like :

struct data {
string data_type_string
string data_type_string2
};

In this case, the struct has 2 of the same data type in a single variable; How is it possible?

The variable struct variable is a customized data type variable or a container of many variables that become data for the variable?

Thanks. (I keep asking me this question and I can not find results online and sorry for my bad English.)

donjuedo
  • 2,475
  • 18
  • 28
Wildzaka02
  • 29
  • 4
  • data_type_string and data_type_string2 are two separate member variables of the struct data – Tom Mar 09 '20 at 11:34
  • @Wildzaka02 You seem to have a confusion between `struct` and `union`. – Fareanor Mar 09 '20 at 11:47
  • In short, think of structs as containers that can contain any number and type of members. If your teacher can't explain it the way you can understand it, you might want to think about [a good C++ book]. – Lukas-T Mar 09 '20 at 13:55

3 Answers3

0

You can think about structure as a list of fields (members). And each field has a specific type. It is possible the two (or all) of fields has the same type.

Evgeny
  • 1,072
  • 6
  • 6
0

A struct or class contain multiple member variables (and functions). You use the names to refer to them, not the type, so having multiple of the same type is not an issue.

data myvar;
myvar.data_type_string = "First String";
myvar.data_type_string2 = "Second String";

Or by position (top to bottom declaration order) in an aggregate initialization.

data myvar = {"First String", "Second String"};

So what you can't have, is two members with the same name.

struct data {
    int mymember;
    std::string mymember; // error
};
Fire Lancer
  • 29,364
  • 31
  • 116
  • 182
0

A struct is basically an aggregate data type (check out other examples here). It basically allows you to group multiple individual variables together. The variables can be of same or mixed datatypes. This might be a useful resource for beginners.

Ladybug
  • 48
  • 8