Hi guys,

Just wondering how i would access a particular variable from an object in an array?? Consider the code:

void Animal::arrayDisplay(){
    Animal ani; 
    Animal* arry[3];
     string n,c;
     int a;
     
     for(int i = 0; i<3; ++i){
        cout <<"Input name:" <<endl ;
        cin>> n;
        cout <<"Input color:" <<endl ;
        cin>> c;
        cout <<"Input age:" <<endl ;
        cin>> a;
     arry[i] = new Animal( n, c, a);
     if (a < 10) { ani.receive( *arry[i]);}
     }
   }
   
   void  Animal::receive(const Animal &){//How do i get age from arry[1]??}

e.g Suppose i want to access the age variable from arry[1], in receive()..how do i do that?

You should be able to use

array[1]->age;

or

(*array[1]).age;

i get the error:

72 C:\Dev-Cpp\oopAssign1.cpp `arry' undeclared (first use this function)

void  Animal::receive(const Animal &)
   {cout<< arry[1]->a <<endl;}

That's because arry is out of scope. in the member function

void Animal::receive(const Animal &){...}

sorry,i thought that when i passed the array object to the function all its variables would be visible to the member function? how do i get it in scope? thanks

If you passing it as a value or reference then that's different..The easiest way is to pass it by value...

Re-write your member function like so:

void  Animal::receive(int age)
   {cout<< age <<endl;}

and call it like so:

if (a < 10) { ani.receive( arry[i]->age);

Please note you allocated memory for your arry elements but didn't free them...

ok..Couple things tho:
1)in my assignment i have to pass an object by constant reference to a member function and i was just wondering if there was anyway of accessing individual variables from the object once it was passed to the member fuction..(im aware that i cannot modify the variables once passed by constant ref but was just wondering can i access them).
2)Is the memory automatically de allocated when the application has run?? Otherwise how do i de allocate (delete array?)

Thanks

This should answer some of your questions..Note I didn't know what an animal was so I used an integer array..

#include <iostream>

void myfunc2(const int & x)
{
  std::cout << x << std::endl;
}

void myfunc(void)
{
  int *mya[3];
  mya[0] = new int(123);
  mya[1] = new int(456);
  mya[2] =  new int(789);
  
  myfunc2(*mya[0]);
  myfunc2(*mya[1]);
  myfunc2(*mya[2]);
  
  delete mya[0];
  delete mya[1];
  delete mya[2];
  
}

int main()
{ 
  myfunc();
  
  return 0;
}
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.