Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

invalid use of non-static data member

Tags:

c++

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?

like image 277
mahmood Avatar asked Mar 06 '12 19:03

mahmood


People also ask

What are non-static data members?

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.

What is a non-static member object?

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)

What is the use of static data member?

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.

How static data member is different from non-static data member?

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.


1 Answers

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.)

like image 76
ruakh Avatar answered Sep 22 '22 06:09

ruakh