How to pass object array to a function? - c++

class department
{
void max() ***HOW TO PASS ARRAY OF OBJECT HERE , WHAT PARAMETERS SHOULD I PASS***
{
}
};
class B : public department {
};
int main()
{
B a[10];
// a.max(a,n); ***HOW TO CALL THIS max FUNCTION***
return 0;
}
I want to pass the array of object a[10] to the max function. How do I call it and pass it?
I don't want to do it like this:
for(i = 0; i < n; i++)
{
a[i].max
}

You implemented max() as a non-static method of department, so you need a department object to call it on, like each B object in your array, eg:
for(int i = 0; i < 10; ++i)
{
a[i].max();
}
If this is not what you want, then max() needs to be taken out of department, or at least made to be static instead. Either way, you will have to change its input parameters to accept the array.
Try something more like this instead:
class department
{
public:
static void max(department *depts, int count)
{
//...
}
};
class B : public department {
};
int main()
{
B a[10];
department::max(a, 10);
return 0;
}
Online Demo
Alternatively:
class department {
};
class B : public department {
};
void max(department *depts, int count)
{
//...
}
int main()
{
B a[10];
max(a, 10);
return 0;
}
Online Demo

How to pass object array to a function?
The parameter of a function cannot be an array in C++. A parameter can be a reference to an array. Alternatively, it is common to pass iterator pointing to an element of an array. Object pointer is an iterator for an array.
department::max() is a non-static member function. It has empty parameter list, so it accepts no arguments at all, except for the implicit class instance that is used as the left hand operand of a member access operator. Since this function accepts no reference to array parameter nor a pointer parameter, there's no way to pass an array as an argument.
Here is an example of a function that does accept a reference to an array as a parameter, and of how to call such function:
void max(B (&arr)[10]);
int main()
{
B a[10];
max(a);
}

Related

How to store a reference to a C-style array in a class?

class Class
{
public:
Class(array[3][3]) //the constructor
{
this->array = array
}
array[3][3];
};
int main()
{
array[3][3] = {...initialization...};
Class object(array[3][3]);
}
I want to make an object, which uses the 2d array and modifies it. I know that C arrays are just pointers to an address, but I couldn't pass it in the constructor no matter how many *, & or [] I write.
The most clever thing I could think of is making an array of POINTERS in the class, and assigning each pointer, to the address of the original array's element via for loop, but then every time I want to modify, or read from the array in main, I have to write for example *array[2][1] = 3.
Any clever solution?
If I finally got the question correctly, you can use a reference to an array:
struct Class {
Class(int (&array)[3][3]) : array_(array)
{}
void set11(int value) {
array_[1][1] = value;
}
int (&array_)[3][3];
};
int main() {
int array[3][3]{};
Class object(array);
object.set11(99);
std::cout << array[1][1]; // Prints 99
}
If that's not what you want, please clarify your question.
Here's how to declare a pointer in your class that can point to the array in main.
class Class
{
public:
Class(int (*array)[3])
{
this->array = array;
}
int (*array)[3];
};
int main()
{
int array[3][3] = { ... };
Class object(array);
}

Send the matrix from class to another class

I have a class that has a matrix
class A{
private:
int matrix[10][5];
};
Also I have other class with method that get matrix and do with it
class B{
public:
void method(/*What to write here?*/){...}
};
So, help to releaze the syntax. How to take matrix from class and send it to other class?
Pass by reference
void method(A& a){...}
If method doesn't need to modify a then pass by const reference
void method(const A& a){...}
Based on the comments below it seems you want something like this
class A
{
public:
void set_coordinates(...) { matrix[...][...] = ...; }
private:
int matrix[10][5];
};
class B
{
public:
void method(A& a) { a.set_coordinates(...); }
};
i.e. pass the object A to method B::method but add sufficient public methods to A so that B can do the work it needs to do. This is what encapsulation is all about.
You can use vector<vector<int> >. That way you can pass them around. Or you can use friend classes, or use double pointers. Let me know if you want any of these I can provide examples.
Using double pointers:
#include <iostream>
using namespace std;
class A{
private:
int **matrix;
public:
A()
{
// since 2D array is array of arrays,
// double pointer is a pointer to array of pointers
// define the matrix, first make matrix point to an array of pointers
matrix = new int*[10];
// now make each element of pointer array
// which is a pointer point to actual array
for(int i=0;i<10;i++)
matrix[i] = new int[5];
// initialize like simple 2D array (another function maybe)
for(int i=0;i<10;i++)
for(int j=0;j<5;j++)
matrix[i][j] = i+j;
}
// note the return-type
int ** getMatrix()
{
return matrix;
}
};
class B{
public:
// wherever you want to access matrix, pass the double pointer
void method(int **matrix){
for(int i=0;i<10;i++)
for(int j=0;j<5;j++)
cout << matrix[i][j] << endl;
}
};
int main() {
// create objects
A a;
B b;
// pass the double pointer to B's method
b.method(a.getMatrix());
return 0;
}

Initialize read only array only once

I have a class that needs to use some big arrays, initialized via some complex functions, that will be the same for every instance and will only be read after initialization.
I searched on SO and found some answers on initializing static arrays like this:
char A::a[6] = {1,2,3,4,5,6};
But in my case I need to calculate the arrays at runtime via some function.
(How) can I do it?
Re
” will be the same for every instance and will only be read after initialization
Producing a value is the job of a function.
Just define a function that returns the data you need.
You can use it to initialize a static data member (or whatever). For a header only module, if that's relevant, you will need to employ solution to the "inline data" problem, e.g. a Meyers' singleton (a function that returns a reference to a local static variable). Like this:
#include <vector>
namespace my {
using std::vector;
inline
auto squares()
-> vector<int>
{
vector<int> result;
for( int i = 1; i <= 12; ++i ) { result.push_back( i*i ); }
return result;
}
class A
{
private:
static
auto a()
-> const vector<int>&
{
static const vector<int> the_values = squares();
return the_values;
}
public:
A(){}
};
} // namespace my
You can't use {} sintaxis in execution time, you can use a method:
class A
{
static vector<char> a;
//...
public:
static void initStatic();
}
void A::initStatic()
{
a.resize( /*put the size here... */);
for (auto& x : a)
x = //something...
}
vector reference: http://en.cppreference.com/w/cpp/container/vector
If you aren't using vectors, this works. The reason I let A::initialize do the work, rather than just calling one of these externally defined functions, is that we can and should expect the data member a to be private.
//Declare a function pointer type, so you can pass it into A's
//an initialization function takes in the array and its size
typedef void (*initFunction) (char A[], int arraySize);
//see http://www.cprogramming.com/tutorial/function-pointers.html
// for more on function pointers
class A
{
public:
void initialize (initFunction myInitFunction);
...
private:
char a[ARRAYSIZE];
};
void A::initialize (initFunction myInitFunction)
{
(*myInitFunction) (a, ARRAYSIZE);
}
...
A myA;
myA.initialize (yourArrayInitializingFunction);
Or maybe your initialization functions don't take in arrays and initialize them, but return arrays:
class A
{
public:
void initialize (const char* aInit);
...
};
void A::initialize (const char* aInit)
{
for (int i = 0; i < ARRAYSIZE: ++i)
a[i] = aInit[i];
}
...
A myA;
myA.initialize (yourArrayReturningFunction ());
If you're using vectors, code is simpler:
class A
{
public:
void initialize (const vector<char>& aInit) { a = aInit; }
...
private:
vector<char> a;
};
My suggestion:
Instead of using a static member variable, use a static member function to provide access to the array.
In the static member function, create a static function variable that can be populated the first time it is needed.
Here's what I am thinking of:
char* A::getArray()
{
static char a[6] = {0};
static bool inited = false;
if ( !inited )
{
// Initialize the array elements
a[0] = ... ;
...
a[5] = ... ;
inited = true;
}
return a;
}

Passing reference of vector of objects as arguments in C++

I'm trying to build a function in which an argument is a reference to a vector of objects. In this case name of the object is 'obj', it is an instance of the class 'Example' and it is a vector as defined in vector class. Object have members like x, y and z.
The reason I'm trying with passing references is because I want to change the value of obj.z by making use of obj.x and obj.y from inside of the function.
#include <vector>
#include <iostream>
using namespace std;
class Example{
public:
double x;
double y;
double z;
Example()
: x(0.0),y(0.0){
}
};
void calculate(Example &obj, int M) {
for(int i = 0; i < M; i++) {
obj[i].z = obj[i].x * obj[i].y;
}
}
int main() {
vector<Example> obj;
int N = 10;
calculate(obj, N);
}
When I run this, I get the following errors:
Inside of the function I have: "Type 'Example' does not provide a subscript operator."
I google'd it and saw that it is related to operator overloading and usage of references. The solution is probably related to dereferencing my object reference inside of the function, but I wasn't able to manage this one right currently.
And the second error is outside of the function, inside the main() at the line where I call the function: "No matching function for call to 'calculate'".
Here, I assume the error is related to the fact that obj is not just an object but a vector of objects, so I should change the argument somehow. But I haven't been able to correct this one up to now as well.
So, to summarize, I want to pass a vector of objects to a function as reference, because I want to be able to change a member of the object inside of the function.
Thank you in advance.
I want to pass a vector of objects to a function as reference
So do that:
void calculate(vector<Example> &obj) {
for(int i = 0; i < obj.size(); i++) {
obj[i].z = obj[i].x * obj[i].y;
}
}
int main() {
vector<Example> obj;
// put some values into it...
calculate(obj);
}
I believe you wanted your function to be
void calculate(vector<Example> &obj, int M)
and not
void calculate(Example &obj, int M)
obj[i]
'obj' isn't an array.
You need to declare it as:
void calculate(Example* obj, int M)
And rather
void calculate(vector<Example>& v)

C++ how to pass array of pointers to a function

I need to pass an array of pointers to a function,
In the example below, there is a class called base and an array of pointers called pool.
How can I pass the array pool to a function called function?
1) in case that I want to be able to change the original array of pointers.
2) in case that I only want to pass a copy of the array of pointers.
Thanks,
class base
{
};
void function (base * pool)
{
}
int main
{
base *pool[40];
function (pool[0]);
return 0;
}
class base
{
public:
int a;
};
void function (base ** pool)
{
for (int i = 0 ; i < 40; ++i)
cout<<pool[i]->a<<' ';
}
int main()
{
base *pool[40];
// Allocate 40 base objects and the 40 base pointers
// point to them respectively
for(int i = 0; i < 40; ++i)
{
pool[i] = new base;
pool[i]->a = i;
}
function (pool);
// free the 40 objects
for(int i = 0; i < 40; ++i)
delete pool[i];
return 0;
}
I added the a member just as an example.
Even better would be
void function (base ** pool, int n)
{
for (int i = 0 ; i < n; ++i)
cout<<pool[i]->a<<' ';
}
and
function (pool, n);
It's not so easy to pass a copy of the array - especially in the case where the objects itself are dynamically allocated.
To pass an array to a function, and maintain the type information about the array, you can use a template:
template <unsigned N>
void function (base *(&pool)[N]) {
}
There is no way to pass a copy of an array, unless it is inside a struct or class. In C++11, you have such a class in STL, called array:
#include <array>
template <unsigned N>
void function (std::array<base *, N> pool) {
pool[0] = 0;
}
base b;
std::array<base *, 40> p;
p[0] = &b;
function(p);
assert(p[0] == &b);