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?

6 Years
Discussion Span
Last Post by gerard4143

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;}

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?)


Edited by oggiemc: n/a


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);
  delete mya[0];
  delete mya[1];
  delete mya[2];

int main()
  return 0;

Edited by gerard4143: n/a

This article has been dead for over six months. Start a new discussion instead.
Take the time to help us to help you. Please be thoughtful and detailed and be sure to adhere to our posting rules.