creating array with user defined datatype

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • anupamsps
    New Member
    • Apr 2007
    • 10

    creating array with user defined datatype

    HI all,

    let me explain the problem:
    In my simulation I am using two class: particle and Container.

    //////////// the outline of particle class/////////////////////
    Sphere.h---->[code=cpp]
    #ifndef SPHERE_H_
    #define SPHERE_H_

    Class Particle
    {
    private:

    double x; // position of the particle
    double Vx; // velocity of the particle
    double _R; // radius of the particle

    public:
    particle()x(0.0 ),Vx(0.0),_R(0. 0){} //default initialisation
    particle(double radius)x(0.0),V x(0.0),_R(radiu s){} // user defined one

    // and the rest of the code goes here.
    };
    #endif
    [/code]
    In another class named "Container" i need to create an array of particle.


    [code=cpp]
    #ifndef CONTAINER_H_
    #define CONTAINER_H_

    #include<vector >
    using namespace std;
    #include"sphere .h"

    class Container
    {
    private:
    vector<particle > HardSphere;

    // and the rest of the program part goes here.

    };

    #endif
    [/code]
    The problem is that in the "container" i want to have the array of particles with desired radius say 1.0. But i always find it invokes the default constructor which set radius to zero. Of course latter on i can run a do loop to set the radius to a desired value. But i was wondering if there is any other way to invoke the different particle constructor from the default one as shown in the particle class. Or using the do loop is the only way.

    thank you
    anupam
    Last edited by sicarie; Jun 14 '07, 05:13 PM. Reason: Please use [code=cpp] and [/code] tags around your code. Thanks!
  • Savage
    Recognized Expert Top Contributor
    • Feb 2007
    • 1759

    #2
    Originally posted by anupamsps
    HI all,

    let me explain the problem:
    In my simulation I am using two class: particle and Container.

    //////////// the outline of particle class/////////////////////
    Sphere.h---->
    #ifndef SPHERE_H_
    #define SPHERE_H_

    Class Particle
    {
    private:

    double x; // position of the particle
    double Vx; // velocity of the particle
    double _R; // radius of the particle

    public:
    particle()x(0.0 ),Vx(0.0),_R(0. 0){} //default initialisation
    particle(double radius)x(0.0),V x(0.0),_R(radiu s){} // user defined one

    // and the rest of the code goes here.
    };
    #endif

    In another class named "Container" i need to create an array of particle.



    #ifndef CONTAINER_H_
    #define CONTAINER_H_

    #include<vector >
    using namespace std;
    #include"sphere .h"

    class Container
    {
    private:
    vector<particle > HardSphere;

    // and the rest of the program part goes here.

    };

    #endif

    The problem is that in the "container" i want to have the array of particles with desired radius say 1.0. But i always find it invokes the default constructor which set radius to zero. Of course latter on i can run a do loop to set the radius to a desired value. But i was wondering if there is any other way to invoke the different particle constructor from the default one as shown in the particle class. Or using the do loop is the only way.

    thank you
    anupam
    How are you creating particles?

    Savage

    Comment

    • anupamsps
      New Member
      • Apr 2007
      • 10

      #3
      Originally posted by Savage
      How are you creating particles?

      Savage
      Savage, i could not follow you. Actually it is a part of a very long program. so i only showed the relevant part. Could you please explain me your question in details.

      just to inform that i access a particle in array as:
      for 2nd particle:
      HardSphere[1].Pos() // for position
      HardSphere[1].Vel() // for velocity
      HardSphere[1].Radius() // for radius.
      etc.

      the function Pos() and Vel() are defined in the particle class:
      which return the position and the velocity respectively.

      Comment

      • Savage
        Recognized Expert Top Contributor
        • Feb 2007
        • 1759

        #4
        Originally posted by anupamsps
        Savage, i could not follow you. Actually it is a part of a very long program. so i only showed the relevant part. Could you please explain me your question in details.

        just to inform that i access a particle in array as:
        for 2nd particle:
        HardSphere[1].Pos() // for position
        HardSphere[1].Vel() // for velocity
        HardSphere[1].Radius() // for radius.
        etc.

        the function Pos() and Vel() are defined in the particle class:
        which return the position and the velocity respectively.
        Sorry,this is how u create array:

        vector<particle > HardSphere;

        particle will envoke defalut constructor unless you call overrided constructor(one that you have created).Your own constructor will be only called if u specify his argument,in this case that's double radius,so try this:

        vector<particle (1.0)> HardSphere;

        Savage

        Comment

        • anupamsps
          New Member
          • Apr 2007
          • 10

          #5
          Originally posted by Savage
          Sorry,this is how u create array:

          vector<particle > HardSphere;

          particle will envoke defalut constructor unless you call overrided constructor(one that you have created).Your own constructor will be only called if u specify his argument,in this case that's double radius,so try this:

          vector<particle (1.0)> HardSphere;

          Savage
          Hi Savage,

          thank you for your suggestion. But Still i am getting compilation error. So let me write the program in full form. That might help to point out the error message.

          /////////////// Sphere.h///////////////////////////////////////////
          [code=cpp]
          //sphere.h sphere definition
          #ifndef SPHERE_H_
          #define SPHERE_H_

          #include<vector >
          using namespace std;

          class particle
          {
          private:

          double r; // position
          double v; // velocity
          double _R ; // radius of a particle


          public:

          particle():r(0. 0),v(0.0),_T(0. 0),_R(0.5){} //default constructor.

          particle(const double x, const double vx, const double Radius):r(x), v(vx) {_R=Radius;}

          particle(const double Radius):_R(Radi us)
          {r=0.0, v=0.0;}

          ~particle(){};

          //talking of postion and velocity form
          Vector & pos(){return r;}
          Vector pos()const{retu rn r;}
          Vector & velocity(){retu rn v;}
          Vector velocity()const {return v;}

          double Radius()const{r eturn _R;}
          friend ostream & operator<<(ostr eam & os, const particle & v);
          };
          typedef particle Particle;
          #endif
          [/code]
          /////////////////////////Sphere.cpp: contains the description of functions///////////
          // definition sphere .h member functions[code=cpp]
          #include<iostre am>
          using namespace std;
          #include"sphere .h"

          // Now we write the particle class function

          ostream &operator<<(ost ream &os, const particle & v)
          {
          cout.setf(ios_b ase::fixed);
          cout.precision( 14);
          cout.setf(ios_b ase::showpoint) ;

          cout<<"Wellcome to particle state:\n";
          cout<<"Radius of the particle: "<<v.Radius()<< "\n";
          cout<<"The Position : "<<v.r<<"\n ";
          cout<<"The Velocity : "<<v.v<<"\n ";

          return os;
          }
          [/code]
          /////////////////////////Here The test program//////////////////////////////////
          // use simple sphere class[code=cpp]
          #include<iostre am>
          #include<vector >
          using namespace std;
          #include"sphere .h"
          int main()
          {
          cout<<"Wellcome to stl particle state\n";
          Particle x;
          Particle y(4.5);


          vector<Particle (4.5)> z; ///LINE NO: 13 the compilation error
          z.resize(5);
          cout<<x<<endl;

          cout<<z[1]<<endl;

          return 0;
          }[/code]

          /////////////////////////////Here is the make file/////////////////////////
          CC = c++
          CFLAGS =
          LDFLAGS =

          Run: sphere.o
          $(CC) $(CFLAGS) testsphere.cpp sphere.o $(LDFLAGS) -o Run

          sphere.o: sphere.cpp
          $(CC) $(CFLAGS) -c sphere.cpp

          //////////////////////////Here is the compilation message////////////////////
          [anupam@localhos t GranAdvSTL2]$ make

          c++ -c sphere.cpp
          c++ testsphere.cpp Myvector.o Varr.o sphere.o -o Run
          testsphere.cpp: In function `int main()':
          testsphere.cpp: 13: error: a call to a constructor cannot appear in a constant-expression
          testsphere.cpp: 13: error: template argument 1 is invalid
          testsphere.cpp: 13: error: template argument 2 is invalid
          testsphere.cpp: 13: error: invalid type in declaration before ';' token
          testsphere.cpp: 14: error: request for member `resize' in `z', which is of non-class type`int'
          testsphere.cpp: 16: error: invalid types `int[int]' for array subscript
          make: *** [Run] Error 1
          ////////////////////////////////////////////////////////////////////////////////////////////////////////

          I really appreciate your help regarding my problem.
          thank you.
          Last edited by sicarie; Jun 14 '07, 05:14 PM. Reason: Please use [code=cpp] and [/code] tags around your code. Thanks!

          Comment

          • weaknessforcats
            Recognized Expert Expert
            • Mar 2007
            • 9214

            #6
            Originally posted by anupmsps
            vector<Particle (4.5)> z; ///LINE NO: 13 the compilation error
            You add Particle obects to the vector this way:
            [code=cpp]
            vector<Particle > z;
            Particle obj(4.5);
            z.push_back(obj );
            [/code]

            Comment

            • anupamsps
              New Member
              • Apr 2007
              • 10

              #7
              Originally posted by weaknessforcats
              You add Particle obects to the vector this way:
              [code=cpp]
              vector<Particle > z;
              Particle obj(4.5);
              z.push_back(obj );
              [/code]
              Thanks for your response. It works perfectly. But i am curious to know whether you can call a user defined constructor in the creation of array like in the above program. But it appears it always call the default constructor.

              Do you think someway we can overload " new " operator to invoke user defined constructor in this case. I tried, but it didn't work.

              anyway, thanks for showing me the simple way out.

              Comment

              • weaknessforcats
                Recognized Expert Expert
                • Mar 2007
                • 9214

                #8
                You need to specify the initial contents when the array is created:

                For an array of int you can:
                [code=cpp]
                int arr[2] = { 1,2};
                [/code]

                Here you specify the intial contents of the array elements between the braces. The compiler does not care if the int value is hard-coded or the result of a function call:
                [code=cpp]
                int arr1[2] = { fx(2), fx(3)};
                [/code]

                where:
                [code=cpp]
                int fx(int in)
                {
                return in;
                }
                [/code]

                So do the same thing with an array of class obects:

                [code=cpp]
                class Test
                {
                private:
                int data;
                public:
                Test(int);
                };
                Test::Test(int in) : data(in)
                {
                }
                [/code]

                Now the trick is to call the constructor as the array elements are created.
                Following the array of int example, you could:
                [code=cpp]
                Test array[2] = {Test(5), Test(6)};
                [/code]

                What this really does is call the class copy constructor. Test(5) creates a Test object. That object is copied to the array element and then it dies.

                Be sure you have the necessary copy constructors if you try this.

                Comment

                Working...