Apr 3, 2018 at 2:49am UTC
Hello, I'm wondering if I can access a function from a class Foo and use it in a function in class bar. Is this possible and if so, how can I pass the argument.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
class Foo {
Private:
int * myArray;
int CAP;
int size;
public :
void insert_to_Array(int val){
size = size + 1; //where size increases by one each insert
myArray[size] = val;
}
};
class bar{
struct node{
int value;
node* right;
node* left;
};
void doSomeWork(node* Ptr, int i);
};
I tried doing something like
void doSomeWork(node* Ptr, int i, Foo name);
for the prototype but that did not help.
I want to be able to call a function from bar but also access the array in the function Foo
1 2 3 4 5 6
void doSomeWork(node* Ptr, int i, something here){
myArray[i] = Ptr->value;
}
I'm not too sure if this is called inheritance, I read over some information about inheritance, but I'm not sure if it's the same.
Last edited on Apr 3, 2018 at 2:51am UTC
Apr 3, 2018 at 3:04am UTC
1 2 3 4
void doSomeWork(node* Ptr, int i, Foo& name){
name.myArray[i] = Ptr->value;
}
Does that work for you? Not exactly sure if I'm understanding your desire.
You'd call it like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int main()
{
Foo foo;
foo.myArray = new int [5];
foo.CAP = 5;
foo.size = 0;
// ...
Bar bar;
Bar::node* node = new Bar::node;
node->value = 42;
bar.doSomeWork(node, 0, foo);
delete [] myArray;
delete node;
}
(untested)
Last edited on Apr 3, 2018 at 3:06am UTC
Apr 3, 2018 at 3:17am UTC
Yes, this appears to work. I am able to access the functions in Foo, via bar.
I was doing something like &name (without adding Foo), but it was just messing it up, so thank you very much.
is this inheritance or is it something else completely?
Last edited on Apr 3, 2018 at 3:18am UTC
Apr 3, 2018 at 3:22am UTC
No, this is not inheritance. That's just passing an object into another function.
Specifically, in doSomeWork, I am passing Foo name by reference , meaning that the original object (Foo foo;) is passed, and not a copy of it.
Last edited on Apr 3, 2018 at 3:23am UTC
Apr 3, 2018 at 3:37am UTC
Ok, cool, Thanks for the help