Why does'nt the following code work?

#include <iostream>

class X
{
public:
  X()
   : m(0)
  { }
	
  virtual ~X()
   { }
	
protected:
  int m;
};

class Y : public X
{
private:
  class Z 
  {
    void do_something() 
    {
       std::cout << m << std::endl;
    }
  };
};

I get invalid use of nonstatic data member ‘X::m’ Thanks for help!

Niels

Recommended Answers

All 2 Replies

You problem is scope. Let me walk through it even if you are familiar with it.

(a) If you want to use m in class X. All is ok.

(b) If you want to use m in class Y. Again all is ok, assuming Y does not define a local varaiant.

(c) If you wan to use m in Z. NOT OK. You would not have been confuse if you has done this:

class X
{ 
   public:
      static int Index;
   protected:
       int m;
};
class Y : public X
{
    void foo()
       {
           std::cout<<"m == "<<this->m<<std::endl;
       }
};

class Z
{
  void write
    { 
       //  Can't use X::m since there is no instance of X here.
      // Can use X::Index (as it is static)
      std::cout<<"Index == "<<X::Index<<std::endl;   
    }   
};

What you have done is defined Z within the scope of Y. That makes it no different to a general definition of Z as above BUT you are forbidden to use Z outside of the implimentation of Y. Therefore, you can only use static instance of X variables, or declare an instance of X and use that.

The only difference between my code and yours is that class Z has slightly larger scope. Unless you define an instance of Z within class Y, then there is no actual instance of Z to do anything with. You can have a whole array of Z if you like but you will have to add it to either a method of Y or as a variable of Y.

Hope that helps.

Thanks!

Niels.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.