AJacinto AJacinto - 1 month ago 7
C++ Question

I am getting An error on my function call, can someone explain why?

I get an error when I try to call my member function to copy the array into another array. Im not sure if I am calling it wrong or what. I think I have the syntax right on most parts but I am also not sure if it matter if the member function is a void or int.

Main.cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "Class.h"

using namespace std;

int main()
{
// Max size of array
int MaxRange = 1000;

// Get System time
unsigned seed = time(0);

// seed random number generator
srand(seed);

// allocate memory for array
int * Array = new int[1000];
int * CopiedArray = new int[1000];

// Randomly generate numbers into array
for (int i = 0; i < 1000; i++)
{
Array[i] = 1 + rand() % MaxRange;
}

//print array
for (int j = 0; j < 1000; j++)
{
cout << Array[j] << endl;
}
CopiedArray = Sort.CopyArray(Array);


return 0;

}

Class.h
#include <iostream>

using namespace std;


class Sort
{

public:
void CopyArray(int * Array);



};

Class.cpp
#include <iostream>
#include "Class.h"

using namespace std;

void CopyArray::CopyArray(int * Array)
{
// Allocate memory for copied array
int * CopiedArray = new int[1000]

//copy date to array
for(int i = 0; i < 1000; i++)
{
CopiedArray[i] = Array[i]
}

cout << " THIS IS THE COPIED ARRAY" << endl;

// print copied array
for (int j = 0; i < 1000; i++)
{
cout << CopiedArray[j] << endl;
}

}

Answer

in your example you are accessing a member function CopyArray without an object you cannot do that. you must create an object of class Sort then use it to access the members. otherwise make CopyArray static and then change it to

class Sort
{
    public:
        static int* CopyArray(int* Array); // to access this function just use the name of class and `::` 
   //   int* CopyArray(int* Array); // to access this function you must have an object of Sort class
};

int* Sort::CopyArray(int * Array)
{
    int * CopiedArray = new int[1000]; // semicolon missin
    // your code processing here
    return CopiedArray;
}


int main()
{

    CopiedArray = Sort::CopyArray(Array); // accessing the static member function `CopyArray`

//   or you can create an object of Sort class but you must also make Copyarray non-static to be able to:
//  Sort theSort;
//  CopiedArray = theSort.CopyArray(Array);

    return 0;
}

* also in your example you are assigning a void to a pointer to int:

    CopiedArray = Sort.CopyArray(Array);// because in your example CopyArray returns void.