0

I am trying to make an Array which will contain pointer to a class. The size of the array will be given from keyboard , so i tried to create the array with the following way :

 class creature
 {
    protected:
      string crt_name ;
      int L ;   
    public:
       creature( int Life = -1 , string Name = "")
        : L(Life) , crt_name(Name){} 

       string get_crt_name ( void )
       { 
          return crt_name ;
       }
 }; 

 class creature_society
 {
    private:
       creature* *A ;
       int noc ;
    public:
       creature_society( int , int ) ;
       ~creature_society() ;
       creature** get_A ( void ){return A ;}
 };

The constructor of creature society will fill the array with creatures made randomly

creature_society::creature_society( int life , int number_of_creatures )
{
   noc =  number_of_creatures ;
   A = new creature*[noc] ;

   creature* temporary ;

   for( int  i = 0 ; i<= number_of_creatures -1 ; i++)
   {
     if ( rand()%100 <= 50) 
        {
            temporary = new good_creature( life , get_unique_name( 3 ) );
            A[i] = temporary ;
        }
        else
        {
            temporary = new bad_creature( life , get_unique_name( 3 ) );
            A[i] = temporary ;
        }
  }
}

Then I try to print the array

    cout << endl << "Printing Society:" << endl ;
    for ( j = 0 ; j <= N -1 ; j++)
    {
       temp = (*( cs1.get_A() + j ))->get_crt_name() ;
    }

The problem is that when i am getting segmentation faults when running on linux , while working fine on Dev C++ ( most of the time )! Any mistakes you pointed out ?

Social Programmer
  • 147
  • 1
  • 4
  • 12

2 Answers2

0

I think you can simply do,

for (int j=0 ; j < N; ++j)
{
   temp = cs1.get_A()[j]->get_crt_name();
}
Pravar Jawalekar
  • 605
  • 1
  • 6
  • 18
0

You don't mention here the classes of bad_creature and good_creature. I assume they inherit creature as a base a class and therefore you should define get_crt_name as a virtual function.

Maybe something went wrong with your get_unique_name function as well. I executed your code in VC2015 and no faulty was found (I replaced ofcourse good creature and bad creature classes with creature and that I replaced get_unique_name with a const string).

Please:

1.Check with your core dump where did your program crash. 2.What output it emitted before the segmentation fault.

For future, class names should always begin with uppercase letters as it is a very common style convention.

Aviv
  • 414
  • 4
  • 16