Hi friends..i have doubt about C++ programming. How to give names for the elemetns in an array of objects...

Recommended Answers

All 4 Replies

Why dont you post the code with the array or where u are experiencing difficulties then we'll take it from there

In my project work i need to create a cubical box and have to place particular number of atoms randomly in the box. For that purpose i have created an array of atom objects. I want to give names for each atom object for their identity...

#include <iostream>
#include<iomanip>
using namespace std;

//Defining two classes..one for silicon(Si) atoms and another one for Oxigen(O2) atoms...
 const int m=100; //numbr of silicon atoms...
 const int n=200;  //number of oxygen atoms...

class Silicon
{
 private:
         int  a;
         float covalent_radius;

} 
//end of the silicon class

class oxygen
{
private:
         int  a;
         float covalent_radius;

 } 
//end of the oxygen class

class Box
{
private: float  depth,length,width:

         float x,y,z //these are three axes with respect to the dimensions of the box.

public: Box(float d, float l, float w )
{

depth=d; 
length=l;
width=w;

x=y=z=d; //because all three dimensions are equal..
}
}//end of the box class

int main()
{
  float covalent-bondlength;

  silicon si[m]; //array of M number of silicon atoms
  oxygen o2[n];  //array of N number of oxygen atoms

  Box cube(1.0,1.0,1.0);  //Cubic box with the given dimensions  
  return 0;
}

well you cant really name the elements of an array, they need to be accessed using the subscript.However to identify each object you can add a unique field in the class and set it for each object. Then when you fetch the object just check for that value to identify it. Or else use a map, so you can add a key for each object stored and then fetch it based on the key.

  1. you could have name as a non-static member in the class. this can be used to give a name to each object.
  2. you could use an enum or a variable to give a name (identifier) for a position in the array.
  3. you could create an alias (reference) with a name (identifier) for an element in the array.
struct Silicon
  {
    Silicon( const char* n ) : _name(n) {}
    const std::string& name() const { return _name ; } 
    /* ... */
    private: const std::string _name ;
  };

  enum { MAD_HATTER=0, CHESHIRE_CAT=1, MARCH_HARE=2,
         GRYPHON=3, LORY=4, N = 5 } ;
  Silicon Si[N] = { "Mad_hatter", "Cheshire Cat", "March Hare",
                    "Gryphon", "Lory" } ;
  Silicon& cheshire_cat = Si[ CHESHIRE_CAT ] ;
  Silicon& gryphon = Si[ GRYPHON ] ;
  int Lorina_Charlotte_Liddell = LORY ;
  Silicon& lorina = Si[ Lorina_Charlotte_Liddell ] ;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.