Hi everyone, im new to C++ and i'm having a few problems with reference.
Here is my example.
Foo.h
1 2 3 4 5 6 7 8
class Foo {
private:
int myA = 0;
int myB = 0;
public:
Foo(int a, int b);
int print_plus();
}
Foo.cpp
1 2 3 4 5 6 7
Foo::Foo(int a, int b) {
myA = a;
myB = b;
}
Foo::print_plus() {
printf("a+b=%i", myA + myB);
}
myApp.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
usingnamespace std;
Foo f; // Here is the doubt, how to just make a reference, not initialize.
int main() {
printf("Starting Foo!");
f(4,5); // Here i want to initalize the object.
anotherFunc(); // And use it anywhere.
otherAnotherFunc(); // Here too.
}
int anotherFunc() {
f.print_plus();
}
int otherAnotherFunc() {
f.print_plus();
}
So my problem is that i know that my Foo class don't have a constructor that accept no parameters, so in "Foo f" statement the compiler complains.
Of course this is just an example my program is a little more complicated, but the issue is the same, how to make a reference to further use on other class or function.
Well...the way you seem to be trying is making a global variable as opposed to a reference...
Here is an example of a reference and how it is different:
1 2 3 4 5 6 7 8 9
void increase(int myInt) {
++myInt;
} //this function doesn't actually increase the int you pass, it increases a copy
//of it, which is destroyed when the function returns
void real_increase(int &myInt) { //passing by reference
++myInt;
} //this actually does increase the actual variable, since you are passing the
//reference instead of a copy
I just realize what i was trying to do. The command that i was looking is the "new". Most of high level languages control the pointers by itself.
Here is what i wanted to do:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
usingnamespace std;
Foo *f; // Pointer to future object.
int main() {
printf("Starting Foo!");
f = new Foo(4,5); // Here i initalize the object with the new.
anotherFunc(); // And use it anywhere.
otherAnotherFunc(); // Here too.
}
int anotherFunc() {
f->print_plus();
}
int otherAnotherFunc() {
f->print_plus();
}