Difference Between "struct Obj* obj" and "Obj* obj"

89 views Asked by At
struct Element{
    Element() {}
    int data = NULL;
    struct Element* right, *left;
};

or

struct Element{
    Element() {}
    int data = NULL;
    Element* right, *left;
};

I was working with binary trees and I was looking up on an example. In the example, Element* right was struct Element* right. What are the differences between these and which one would be better for writing data structures?

I was looking up from this website: https://www.geeksforgeeks.org/binary-tree-set-1-introduction/

2

There are 2 answers

0
Ted Lyngmo On BEST ANSWER

In C++, defining a class also defines a type with the same name so using struct Element or just Element means the same thing.

// The typedef below is not needed in C++ but in C to not have to use "struct Element":
typedef struct Element Element;
struct Element {
    Element* prev;
    Element* next;
};

You rarely have to use struct Element (other than in the definition) in C++.

There is however one situation where you do need it and that is when you need to disambiguate between a type and a function with the same name:

struct Element {};
void Element() {}

int main() {
    Element x;  // error, "struct Element" needed
}
0
user12002570 On

In C, struct keyword must be used for declaring structure variables, but it is optional(in most cases) in C++.

Consider the following examples:

struct Foo
{
    int data;
    Foo* temp; // Error in C, struct must be there. Works in C++
};
int main()
{
    Foo a;  // Error in C, struct must be there. Works in C++
    return 0;
}

Example 2

struct Foo
{
    int data;
    struct Foo* temp;   // Works in both C and C++
};
int main()
{
    struct Foo a; // Works in both C and C++
    return 0;
}

In the above examples, temp is a data member that is a pointer to non-const Foo.


Additionally, i would recommend using some good C++ book to learn C++.