I have the following code:
#include <iostream>
using namespace std;
struct S {
S(int i): I(i) { }
int & v () { return I; }
private :
int I;
};
S s1 (1);
int main() {
cout << s1.v() << "\n";
return 0;
}
And I get the output:
1
I am confused as to how it is working. For example with s1 it is calling the constructor S(int i) but how is it sub-classing I and calling its constructor when there is no I class and how is the private variable I getting assigned a number when there has been nothing assigned to it? Also, if v() returns int& (a reference therefore, I would think it would print out a memory location but it gives 1 consistently).
Sorry if this sounds stupid can’t figure it out.
It seems you have multiple questions:
The struct is not subclassing
I, it is simply using Initialization Lists to construct the I variable. The same could have been done with the constructorS(int i) { I = i;}.It is getting assigned in the constructor, see #1.
You are confusing references and pointers. References pretend to act like regular value passed numbers. Pointers, returning
int *with a function such asint * v () { return &I; }would print out the address of the variable unless you dereference them with the * symbol. References automatically dereference themselves.