C++/CLI: Value Class Types, Ref Class Type Vs C++: Class as ref, const Ref and Copy RRS feed

  • General discussion

  • I usually work in C++ but recently I started working on C++/CLI and C#. I have some doubt about following.

     in C++ lets take i have a class Point which contain XYZ and a class PointConatainer wich conatian Points.

    class Point
           Point(double X = 0, double y = 0, double z = 0);
           double&      x     ();
           double       x     ()const;
           double&      y     ();
           double       y     ()const;
           double&      z     ();
           double       z     ()const;
           double    XYZ[3];
    class PointContainer 
           const Point&    point    ( int index)const;
           Point  mPoint[100];
    PointContainer  container;

    in this case no one can change the value of the point in the conatainer class but can ref it so no additional copy of point is created while acessing it by


    but if user want to use the value and do the operation over it, then he can do it like

    Point pt = container.point(0);
    pt.x() = 10.0;

    even in this case it will modify the local copy of point not the point in the container.
    To achieve the same result in C++/CLI I am confuced

    1) As i think there is no concept on const i guess.

    2) I should cerate Point as value class or ref class. as in ref class there will be no additional copy is create but user can modify the data and if I create value class there will be a new copy of Point every time but then I can't provide the default constructor (I know value class is initialize by zero automatically but if I want specific value for some reason). And one way I can do I can make point as ref class and in container I will return new instance of point i.e.

    Point^ point(int index)
       return gcnew Point(mPoint[index]);
    Is there a better way to do the same? As I would like to have point as a value class type behaviour

    Saturday, May 19, 2012 9:27 AM

All replies

  • 1) C++/CLI support for const is limited, you can have const variables, function parameters and return values but you can't have const methods.

    2) There's no way to get around the default constructor restriction for value types. If you absolutely need this then you have to use a ref class but in the case of Point I think it's overkill.

    Saturday, May 19, 2012 10:19 AM
  • Sometimes you can use “tracking references” (%) that behaves like a ‘&’ reference []:

    Point % point( int index )


        return mPoint[index];


    Saturday, May 19, 2012 2:05 PM