Talk About Network

Google


Register and Login
Nick
Password
Register create new account Sign up is FREE and you can post replies, new topics, bookmark posts and more!
Recover lost password


Programming > C++ > Re: nested clas...
Latest [ Topics | Posts ] Archive Post A New Topic Post a Reply
<< Topic < Post Post 2 of 2 Topic 43692 of 48417
Post > Topic >>

Re: nested class inheriting from outer class

by Michael.Boehnisch@[EMAIL PROTECTED] Mar 5, 2008 at 10:14 AM

On 5 Mrz., 10:18, Richard Lee <prodigyn...@[EMAIL PROTECTED]
> wrote:
> The following does compile, but has other problems:
[..]
> The problem is that if you later try to refer to class A, the compiler
> claims it is not a class, it's a namespace.  Aren't cl***** by
> definition namespaces?  Something seems broken here.

Cl***** are *not* namespaces.

namespace A { int x; } declares and instantiates an int variable with
name x that can be accessed as A::x without further preparation.

#include <iostream>

namespace A { int x; }

int main() {
    A::x = 42;
    std::cout << "A::x is " << A::x << std::endl;
    return 0;
}

class A { public: int x; }; only defines a new type of objects and no
instance at all. Thus, you cannot use A::x e.g. in you main program.
You first need to create an object of type "class A":

#include <iostream>

class A { public: int x; };

int main() {
   A obj;
   obj.x = 42;
   std::cout << "obj.x is " << obj.x << std::endl;
   return 0;
}

You can create more objects of type "class A" and each will provide a
new and separate instance of the member variable x.
Note also, you need to reference to x with the "." operator and not
with "::".

You can create member variables which are shared between all instances
of a class and get accessed in a way that looks similar to the
namespace access operator:

#include <iostream>

class A { public: static int x; }
int A::x;

int main() {
   A::x = 42;
   std::cout << "A::x is " << A::x << std::endl;
   return 0,
}

This looks a little more similar to the namespace example but note,
class A is still just a type and A::x needs to be instantiated
separately.

I hope the difference became more clear to you.

best,

   Michael
 




 2 Posts in Topic:
Re: nested class inheriting from outer class
Richard Lee <prodigyne  2008-03-05 09:18:05 
Re: nested class inheriting from outer class
Michael.Boehnisch@[EMAIL   2008-03-05 10:14:50 

Post A Reply:
  Go here to Signup

AddThis Feed Button


About - Advertising - Contact - Frequently Asked Questions - Privacy Policy - Terms of Use - Signup

Contact
tan12V112 Fri Nov 21 10:15:24 CST 2008.