Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C++ structs and classes

  1. Aug 21, 2006 #1

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    I was trying to understand how structs differ from classes in c++ and I came across this:
    http://carcino.gen.nz/tech/cpp/struct_vs_class.php
    I was wondering.. when would you choose to use a struct in c++ rather than a class?
     
  2. jcsd
  3. Aug 21, 2006 #2

    chroot

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Structs are really hold-overs from C, the predecessor of C++. Structs still exist in the C++ language mainly just to keep it backward-compatible with C. You won't find many C++ programmers using structs in C++.

    - Warren
     
  4. Aug 21, 2006 #3

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    thanks, Warren. There was a chapter on structs in my book, but we never covered them, so I couldn't understand what that was all about. We stopped just before that and started learning classes.

    One other thing I am confused about is why an array is called a data structure, but a structure (struct) is called a data type. They both seem to have elements that are organized in a certain way.
     
    Last edited: Aug 21, 2006
  5. Aug 21, 2006 #4

    chroot

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    The terms "data structure" and "data type" are certainly thrown around a bit sloppily, and sometimes are even used somewhat interchangably. A lot of the distinction is in their context.

    All variables in C have a specific data type. For example, "char c" declares a new variable, named 'c,' of type char. A data type can be a primitive type, provided by the compiler (e.g. int, char, float, double), or they can be user-defined and may contain numerous internal fields. Classes and structs are syntactical mechanisms used to define new types.

    "Data structures," on the other hands, are aggregations of multiple variables, of potentially different types. An array is a "data structure," because it contains many elements of the same type.

    Here are some examples of the ambiguity:

    Code (Text):

    struct foo {
        char c[10];
    }

    struct foo myFoo;

    myFoo.c[0] = 0;
    In this case, "foo" would be referred to by most programmers as a type, though it really contains nothing more than an array of characters.

    Code (Text):

    typedef char bar;

    bar myBar[10];

    myBar[0] = 0;
    In this case, bar would be referred to as a type, but myBar would be referred to as a data structure.

    These two "approaches" would allocate the same memory, and behave essentially the same way -- in fact, both programs would probably produce identical machine code under many compilers.

    The only difference, the reason why people call foo a data type and myBar a data structure, is the syntax used for each. foo is declared in such a way that suggests it is meant to be used as a type -- it internalizes the array. myBar is declared in such a way that it is meant to be used as a data structure, exposing the array directly.

    - Warren
     
    Last edited: Aug 21, 2006
  6. Aug 21, 2006 #5
    you will use structs for classes which every member is public.
    In most of the 3D engines that I have taken apart, they apply this to the math classes that are used alot like vectors: struct { x,y,z }, and simple geometries like lines and planes as well as to teh colour class struct {r,g,b}. Note that I did not actually use the correct syntax, iwas just providing examples. Sometimes people like to leave certain math functions as global namespace functions. Like Distance & Intersection and implement old C style structs where there are no member functions with teh struct. Others like to have complete access to the struct but still include the functions as member functions rather than global scope functions. I have been through various phases of a simple 3D engine to see what the difference between pure C(functional), C/C++ mix, pure OO. I still don't know what the difference is besides convenience in Coding. So I stick with the middle Blending both Functional & OO. with C++ compilers you can do alot of function/operator overload in the global namespace, so i get the best of both worlds. Use OO for more complicated classes like A Renderer, DataStructures, EngineApp, SceneManagement stuff. And use mostly functional programming for all the math aspects.
     
  7. Aug 21, 2006 #6

    chroot

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    neurocomp:

    There is no specific reason why those programmers used the keyword "struct," except for perhaps historical reasons or for nostalgia. Many programmers associate "struct" with C structs, which no longer actually exist in C++. In C++ terms, a C struct is just a degenerate class with nothing but member variables.

    - Warren
     
  8. Aug 21, 2006 #7
    Chroot: how does a DS potentially different types? Are you referring to polymorphism in which case thers a common base type? Never seen anyone describe DS with these words before "aggregations of multiple variables" cool.
     
  9. Aug 21, 2006 #8

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    ah! I think I am starting to see the light. Thanks!
     
  10. Aug 21, 2006 #9

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Is this better than using a class and making all its members public? sorry if that's a naive question.
     
  11. Aug 21, 2006 #10
    chroot: from what i've seen of the C++struct use, people do this

    struct SVector {
    REAL x,y,z;
    Add(SVector x);
    operator(SVector v);
    };
    struct SLine {
    SVector p, v;
    REAL Dist(SVector);
    };
    Which is not C structs, because you can't have function members in C struct or to my knowledge(though you can have function pointers) You are probably right in what you have said about the nostalgia thing. I wouldn't know becuase i've only begun coding these past 2 years in C++.
     
  12. Aug 21, 2006 #11
    MathIsHard: wouldn't know...the syntax differs only by
    struct StructName {};
    class ClassName { /*no code above this public*/ public: .....};

    You can inherit from both.
     
  13. Aug 21, 2006 #12

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    ok, guess it is just a matter of preference then. thanks.
     
  14. Aug 21, 2006 #13

    rcgldr

    User Avatar
    Homework Helper

    Edit: update - I was thinking C structures, not C++ structures. The text you quoted is correct, the only difference is the default of public or private for the members.

    Original text:
    As previously mentioned, classes can have functions as members. They also have two automatic functions, one for creation, and one for deletion.

    With structures, you have to use pointer to functions to get the equivalent.

    Structure members can't be over ridden with new names or members, but class member can be. For example there is a windows class that provides member functions for all the windows message types, and a programmer overrides a sub-set of these by declaring functions to handle some of the message types in his code.
     
    Last edited: Aug 22, 2006
  15. Aug 21, 2006 #14

    chroot

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Jeff,

    Everything you said is, in fact, wrong. Try compiling the following program with a C++ compiler:

    Code (Text):
    #include <iostream>

    using namespace std;

    struct foo {
        foo();
        virtual void bar();
    };

    foo::foo() {
        cout << "Structs can have ctors." << endl;
    }

    void foo::bar() {
        cout << "Structs can have member methods." << endl;
    }

    struct foo_child : foo {
        void bar();
    };

    void foo_child::bar() {
        cout << "Structs can even have inheritance." << endl;
    }

    int  main(void) {
        foo f;
        f.bar();
       
        foo_child fc;
        fc.bar();
       
        return 0;
    }
    - Warren
     
  16. Aug 22, 2006 #15

    rcgldr

    User Avatar
    Homework Helper

    I was trying to compare C structures versus C++ classes. In the case of C++ structures, you're correct, there isn't a lot of difference.

    Normally I define structures with typedefs, using leading underscores for the struct, and no leading underscore for the typedef (Microsoft standard).

    typedef struct _EXAMPLE{
    ...
    }EXAMPLE, *PEXAMPLE;

    Curious about this, do non-Microsoft compliers allow struct reference within stuctures?
    For example, this case for usage with a single linked list of structures:

    typedef struct _EXAMPLE{
    struct _EXAMPLE *pNext;
    ...
    }EXAMPLE, *PEXAMPLE;
     
    Last edited: Aug 22, 2006
  17. Aug 22, 2006 #16

    chroot

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    As per the title, this thread is about structs in C++.

    - Warren
     
  18. Aug 22, 2006 #17

    rcgldr

    User Avatar
    Homework Helper

    Based on the quoted text, use a struct when most or all of the members will be public, and classes when not. ... or you could just use classes and declare everything public manually.
     
  19. Aug 22, 2006 #18

    rcgldr

    User Avatar
    Homework Helper

     
  20. Aug 22, 2006 #19
    jeff Reid: "when most or all of the members will be public" ...its all not most. any member of a struct in C++ is always public.
     
  21. Aug 22, 2006 #20

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    unless you make it private. :smile:
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?