ashwin shrestha
ashwin shrestha

Reputation: 107

How access member function from arrayobject in a loop

I am trying to access public function get_data(), to generate an output "here ", to see if creating dynamic object from array of object..so how can i do that.

#include<iostream>
#include <conio.h>

using namespace std;
int counts = 0;
int no_of_array;

class Matrix
{
    int **dynamicArray;

public:

    Matrix()
    {
        counts++;
        dynamicArray = new int *[3];

        for (int i = 0; i < 3; i++)
        {
            dynamicArray[i] = new int[3];
        }
    }

    void get_data(){

        cout << "here \n";
    }
};

int main()
{
    int newvalue = 1;
    int i;
    Matrix *array_object[100];
    int choice;
    while (newvalue == 1){
        cout << "Enter your choice \n 1. for 2 matrix addition \n 2. for 2 matrix multiplication \n";
        cin >> choice;
        if (choice == 1)
        {
            cout << "how many array to add \n";
            cin >> no_of_array;
            for (i = 0; i <= no_of_array; i++)
            {
                array_object[i] = new Matrix();
            }

            for (i = 0; i < no_of_array; i++)
            {
                array_object[i].get_data();

            }
        }
        else if (choice == 2)
        {
            Matrix mul;
            //  mul.multiplication();        
        }
        else
            cout << "Do enter correct choice \n";

        cout << "press 1 to enter again and 0 to exit \n";
        cin >> newvalue;
    }
    getch();
    return 0;
}

I am trying to check here, if for all the objects created, get_data function will be called or not... but instead i get a error get_data has not been decleared.

Upvotes: 2

Views: 88

Answers (2)

mazhar islam
mazhar islam

Reputation: 5619

Use array_object[i]->get_data(); instead of array_object[i].get_data();.

The DOT(.) operator is used when an object try to access its class member functions/variables whereas Arrow(->) operator is used if the object is a pointer.

Now, you declared

Matrix *array_object[100]; 

Which means array_object is an array of Matrix pointers. Hence you need to use Arrow(->) instead of DOT(.) operator.

Upvotes: 1

HadeS
HadeS

Reputation: 2038

Matrix *array_object[100]; is pointer to array of type Matrix. Inorder to access class member using pointer you should use -> operator.

for(i=0;i<no_of_array;i++)
{
       array_object[i]->get_data();
}

Upvotes: 1

Related Questions