473,385 Members | 1,542 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

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---->
Expand|Select|Wrap|Line Numbers
  1. #ifndef SPHERE_H_
  2. #define SPHERE_H_
  3.  
  4.     Class Particle
  5.    {   
  6.        private:
  7.  
  8.         double x;    // position of the particle
  9.         double Vx;  // velocity of the particle
  10.        double _R;   // radius of the particle
  11.  
  12.         public:
  13.        particle()x(0.0),Vx(0.0),_R(0.0){} //default initialisation
  14.        particle(double radius)x(0.0),Vx(0.0),_R(radius){} // user defined one
  15.  
  16.  //   and the rest of the code goes here.
  17.     };    
  18. #endif
  19.  
In another class named "Container" i need to create an array of particle.


Expand|Select|Wrap|Line Numbers
  1.  #ifndef CONTAINER_H_
  2. #define CONTAINER_H_
  3.  
  4. #include<vector>
  5. using namespace std;
  6.  #include"sphere.h"
  7.  
  8.    class Container
  9.     {
  10.         private:
  11.        vector<particle> HardSphere;
  12.  
  13.   // and the rest of the program part goes here.
  14.  
  15.    };
  16.  
  17. #endif
  18.  
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
Jun 13 '07 #1
7 3866
Savage
1,764 Expert 1GB
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),Vx(0.0),_R(radius){} // 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
Jun 13 '07 #2
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.
Jun 13 '07 #3
Savage
1,764 Expert 1GB
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
Jun 13 '07 #4
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///////////////////////////////////////////
Expand|Select|Wrap|Line Numbers
  1. //sphere.h sphere definition
  2. #ifndef SPHERE_H_
  3. #define SPHERE_H_
  4.  
  5. #include<vector>
  6. using namespace std;
  7.  
  8. class particle
  9. {
  10. private:
  11.  
  12.       double r;  // position 
  13.       double v;  // velocity 
  14.       double _R ;  // radius of a particle
  15.  
  16.  
  17. public:
  18.  
  19.       particle():r(0.0),v(0.0),_T(0.0),_R(0.5){}  //default constructor.
  20.  
  21.       particle(const double x,  const double vx, const double Radius):r(x), v(vx)  {_R=Radius;} 
  22.  
  23.       particle(const double Radius):_R(Radius)
  24.                {r=0.0, v=0.0;}
  25.  
  26.       ~particle(){};
  27.  
  28. //talking of postion and velocity  form     
  29.      Vector & pos(){return r;}
  30.      Vector  pos()const{return r;}
  31.      Vector & velocity(){return v;}
  32.      Vector  velocity()const{return v;}
  33.  
  34.      double Radius()const{return _R;}
  35.      friend ostream & operator<<(ostream & os, const particle & v);
  36. };
  37. typedef particle Particle;
  38. #endif
  39.  
/////////////////////////Sphere.cpp: contains the description of functions///////////
// definition sphere .h member functions
Expand|Select|Wrap|Line Numbers
  1. #include<iostream>
  2. using namespace std;
  3. #include"sphere.h"
  4.  
  5. // Now we write the particle class function
  6.  
  7.     ostream &operator<<(ostream &os, const particle & v)
  8.      {
  9.            cout.setf(ios_base::fixed);
  10.            cout.precision(14);
  11.            cout.setf(ios_base::showpoint);
  12.  
  13.            cout<<"Wellcome to particle state:\n";
  14.            cout<<"Radius of the particle: "<<v.Radius()<<"\n";
  15.            cout<<"The Position : "<<v.r<<"\n";
  16.            cout<<"The Velocity : "<<v.v<<"\n";
  17.  
  18.             return os;
  19.     }
  20.  
/////////////////////////Here The test program//////////////////////////////////
// use simple sphere class
Expand|Select|Wrap|Line Numbers
  1. #include<iostream>
  2. #include<vector>
  3. using namespace std;
  4. #include"sphere.h"
  5. int main()
  6. {
  7.     cout<<"Wellcome to stl particle state\n";
  8.     Particle x;
  9.     Particle y(4.5);
  10.  
  11.  
  12.     vector<Particle(4.5)> z;      ///LINE NO: 13 the compilation error 
  13.     z.resize(5);
  14.     cout<<x<<endl;
  15.  
  16.     cout<<z[1]<<endl;
  17.  
  18.     return 0;
  19. }
/////////////////////////////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@localhost 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.
Jun 13 '07 #5
weaknessforcats
9,208 Expert Mod 8TB
vector<Particle(4.5)> z; ///LINE NO: 13 the compilation error
You add Particle obects to the vector this way:
Expand|Select|Wrap|Line Numbers
  1. vector<Particle>  z;
  2. Particle  obj(4.5);
  3. z.push_back(obj);
  4.  
Jun 13 '07 #6
You add Particle obects to the vector this way:
Expand|Select|Wrap|Line Numbers
  1. vector<Particle>  z;
  2. Particle  obj(4.5);
  3. z.push_back(obj);
  4.  
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.
Jun 14 '07 #7
weaknessforcats
9,208 Expert Mod 8TB
You need to specify the initial contents when the array is created:

For an array of int you can:
Expand|Select|Wrap|Line Numbers
  1. int arr[2] = { 1,2};
  2.  
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:
Expand|Select|Wrap|Line Numbers
  1. int arr1[2] = { fx(2), fx(3)};
  2.  
where:
Expand|Select|Wrap|Line Numbers
  1. int fx(int in)
  2. {
  3.     return in;
  4. }
  5.  
So do the same thing with an array of class obects:

Expand|Select|Wrap|Line Numbers
  1. class Test
  2. {
  3.      private:
  4.         int data;
  5.      public:
  6.         Test(int);
  7. };
  8. Test::Test(int in) : data(in)
  9. {
  10. }
  11.  
Now the trick is to call the constructor as the array elements are created.
Following the array of int example, you could:
Expand|Select|Wrap|Line Numbers
  1. Test array[2] = {Test(5), Test(6)};
  2.  
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.
Jun 14 '07 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: Phil Powell | last post by:
if (is_array($_POST)) { foreach ($this->getAssocSectionsObjArray($key, $dbAP) as $obj) { print_r($obj); print_r(" in array? "); print_r(in_array($obj, $result)); print_r("<P>"); if...
11
by: Magix | last post by:
Hi, what is wrong with following code ? typedef struct { word payLen; datatype data; } msg_type;
8
by: Nanda | last post by:
hi, I am trying to generate parameters for the updatecommand at runtime. this.oleDbDeleteCommand1.CommandText=cmdtext; this.oleDbDeleteCommand1.Connection =this.oleDbConnection1;...
4
by: UJ | last post by:
I have a datatype that I want to use as a type for a column (It's an enumeration.) but I can't get the syntax right. Can you even do it? Or do I need to do it as a string and convert it back and...
2
by: Matt | last post by:
Stop me if you've heard this one... I want to create a "data dictionary" table of all my user tables in a certain database. The data dictionary (my version) will contain columns such as...
3
by: Bartholomew Simpson | last post by:
I am writing some C++ wrappers around some legacy C ones - more specifically, I am providing ctors, dtors and assignment operators for the C structs. I have a ton of existing C code that uses...
1
by: srinit | last post by:
I am new to sql2005... how can i create user defined datatype containing different types ex : address with name as varchar. ...
11
by: harsh123 | last post by:
I wish to add a new datatype to help me in doing mathametical computations.We all know that the system has got limited amount of memory ie we cannot create an array of very big size. for example a....
5
by: Shalini Bhalla | last post by:
I am trying to create a table in mysql using php , but the problem is that no. of fields and their datatype is taken from user in input form in am array .so , i want to know that how should i create...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.