Can the constructer declared before the member variable alter its value?
I thought only the code below works,
struct test {
int a;
test(int t): a(t) {}
};
but I found the code below also works.
struct test {
test(int t): a(t) {}
int a;
};
Usually, in function, we cannot use the variable that is not declared. Why the code above is OK?
CodePudding user response:
Actually in C there's an exception that there's no need for forward declaration of functions and variable of a class/struct.
You can see my such examples on the internet like this:
class foo
{
public:
foo(int x) : my_var(x) {}
private:
int my_var;
};
The above is 100% valid.
You can also call a function of a class before it is defined like:
class bar
{
public:
bar()
{
this->my_below_func();
}
int my_below_func()
{
return 1;
}
};
Always remember that these tricks aren't going to work outside C classes/structs, you will need forward declaration of your functions and variables.