Thread: classes data storage (noob question)

  1. #1
    Registered User
    Join Date
    Apr 2011

    classes data storage (noob question)

    ok, so I just started working with classes when I came across something I'm not sure how to interpreter.

    I was doing an exercise that asked to build a class to store 3d coordinates and an outside fuction to compute the dot product (and some vague allusion to pass-by-ref that I'm not sure I got right).

    so I build the class:
    class point
        double x,y,z;
        void set(double a, double b, double c)
            {x=a; y=b; z=c;}
        double* xref() {return &x;}
        double* yref() {return &y;}
        double* zref() {return &z;}
    and then start noticing something strange when I'm working on the function... a few tests later I come up with this:
    double dot_product(double *v1, double *v2)
       {return v1[0]*v2[0]+v1[1]*v2[1]+v1[2]*v2[2];}
    (to which I'm feeding the ONLY ".xref()" results.)

    I've recompiled this a few times and this always work....

    so my question is: Is it built into the language that the variables in a class are stored in adjacent memory blocks? or my compiler just decided to do so and therefore I can't rely on it to do so in the future?

  2. #2
    Registered User
    Join Date
    Apr 2011
    ...I'm feeding ONLY the ".xref()"...

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    C++ classes - Wikipedia, the free encyclopedia
    While your class contains only POD data (of the same type), you can generally assume that member variables are stored in declaration order, in consecutive locations (as if in an array).

    But it's an extremely fragile assumption, as it won't take much to be added to your class to break it.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Registered User
    Join Date
    Apr 2011
    so even though it works (this time) it's not a built in feature and I should recode it as I inicially intended to.

    tks for the help

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Noob Question about classes
    By johndeaton in forum C++ Programming
    Replies: 2
    Last Post: 03-22-2012, 12:37 PM
  2. Noob question about classes
    By Dondrei in forum C++ Programming
    Replies: 12
    Last Post: 06-28-2008, 03:56 PM
  3. (noob) Question about classes
    By abachler in forum Windows Programming
    Replies: 6
    Last Post: 09-22-2007, 04:27 AM
  4. Data Storage Question, and Dynamic variables?
    By Zeusbwr in forum C++ Programming
    Replies: 5
    Last Post: 10-21-2004, 11:01 PM
  5. need help with storage classes
    By datainjector in forum C Programming
    Replies: 1
    Last Post: 07-03-2002, 04:27 PM