I am beginner in c++. Here is my doubt why in this program they are again creating struct variable from the previously created struct object ? Here is the example:
typedef struct prog1
{
int a,b;
}*obj1;
int main()
{
obj1 moc=new prog1(); // why again creating object for *obj1 object?
moc->a=10; // why dont we use obj1 -> a=10;
}
thanks
To make it more clear use an alias declaration instead of the typedef definition.
struct prog1
{
int a,b;
};
using obj = struct prog1 *;
So the name obj
is an alias for the type struct prog1 *
. obj
is not a variable.
So in this declaration
obj1 moc;
there is defined the variable moc
with the type obj
. This declaration is equivalent to the following declaration
prog1 *moc;
That is there is declared a pointer of the type prog1 *
.
Pay attention to that the pointer is not initialized. So it has indeterminate value. As a result the following statement
moc->a=10;
invokes undefined behavior.