For a code like this:
class foo { protected: int a; public: class bar { public: int getA() {return a;} // ERROR }; foo() : a (p->param) };
I get this error:
invalid use of non-static data member 'foo::a'
currently the variable a
is initialized in the constructor of foo
.
if I make it static, then it says:
error: 'int foo::a' is a static data member; it can only be initialized at its definition
However I want to pass a value to a
in the constructor. What is the solution then?
Non-static data members are the variables that are declared in a member specification of a class. a non-static data member cannot have the same name as the name of the class if at least one user-declared constructor is present.
A non-static member function is a function that is declared in a member specification of a class without a static or friend specifier. ( see static member functions and friend declaration for the effect of those keywords)
A typical use of static members is for recording data common to all objects of a class. For example, you can use a static data member as a counter to store the number of objects of a particular class type that are created.
If a data is declared as static, then the static data is created and initialized only once. Non-static data members are created again and again. For each separate object of the class, the static data is created and initialized only once.
In C++, unlike (say) Java, an instance of a nested class doesn't intrinsically belong to any instance of the enclosing class. So bar::getA
doesn't have any specific instance of foo
whose a
it can be returning. I'm guessing that what you want is something like:
class bar { private: foo * const owner; public: bar(foo & owner) : owner(&owner) { } int getA() {return owner->a;} };
But even for this you may have to make some changes, because in versions of C++ before C++11, unlike (again, say) Java, a nested class has no special access to its enclosing class, so it can't see the protected
member a
. This will depend on your compiler version. (Hat-tip to Ken Wayne VanderLinde for pointing out that C++11 has changed this.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With