Jun 3, 2018 at 2:02pm UTC
Hello!
Okay assume you have a class:
1 2 3 4 5 6 7 8 9 10 11
class Foo
{
private :
int a;
int b;
public :
Foo(int argument);
~Foo();
friend Class Bar;
};
and a second class:
1 2 3 4 5 6
class Bar
{
...
public :
static void change_a_b(int argument, Foo fooObject);
};
With the following function
1 2 3 4 5
void Bar::change_a_b(int argument, Foo fooObject)
{
fooObject.a = ...;
fooObject.b = ...;
};
So what I want to do is create a Foo object like so:
Foo fooObject(argument);
where
argument
is an int.
But
Bar::change_a_b(int argument, Foo fooObject)
function would be inside
Foo::Foo(int )
constructor.
Since the object would be in the process ob being created, how can you pass it to a function, inside the constructor?
EDIT: to make thinks clearer, that's what I mean:
1 2 3 4 5 6
Foo:Foo(int argument)
{
Bar::change_a_b(argument,/*FOOOBJECT HERE*/ )
...
}
Thank you in advance,
Regards,
Hoogo
Last edited on Jun 3, 2018 at 2:12pm UTC
Jun 3, 2018 at 5:55pm UTC
Whenever the implementation looks complex, you have to ask yourself: Is this really the best possible design? Is there no simpler alternative?
Jun 3, 2018 at 7:29pm UTC
Not really, I scratched my head for a while and I really have to do it that way. It's for a game I'm working on. Why are you asking? Is there no way to possibly do it that way?
Jun 3, 2018 at 8:10pm UTC
There's probably a better way. But this may do what you're asking for.
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
#include <iostream>
class Foo; // forward reference
class Bar {
public :
static void setFoo(int arg, Foo& foo);
};
class Foo {
int a, b;
public :
Foo(int arg) { Bar::setFoo(arg, *this ); }
void print() { std::cout<< a <<',' << b <<'\n' ; }
friend class Bar;
};
void Bar::setFoo(int arg, Foo& foo) {
foo.a = arg / 2;
foo.b = arg * 2;
}
int main() {
Foo f(42);
f.print();
}
Last edited on Jun 3, 2018 at 8:11pm UTC
Jun 4, 2018 at 5:40am UTC
@tbp
Thanks a lot, this is exactly the answer I was looking for!
Jun 4, 2018 at 6:00am UTC
EDIT: Well my complier is telling me that my function "does not take 2 arguments" even though I declared it and defined it correctly. The function call is correct too. I don't understand.
Jun 4, 2018 at 6:12am UTC
We can't see your code nor entire compiler messages, so how could we comment?
Jun 4, 2018 at 1:25pm UTC
@keskiverto
My bad I was going to post the whole code but I had to go. I managed to sort it, turned out i had circular dependencies messing the whole thing up.
Thanks you a lot for your time though.
Regards,
Hoogo.