Show: Object Pascal C++
Display Preferences

Member Scope

From Appmethod Topics
Jump to: navigation, search

Go Up to Member Scope Index

In Inline functions and exceptions, the expression X::func() in the example uses the class name X with the scope access modifier to signify that func, although defined "outside" the class, is indeed a member function of X and exists within the scope of X. The influence of X:: extends into the body of the definition. This explains why the i returned by func refers to X::i, the char* i of X, rather than the global int i. Without the X:: modifier, the function func would represent an ordinary non-class function, returning the global int i.

All member functions, then, are in the scope of their class, even if defined outside the class.

Data members of class X can be referenced using the selection operators . and -> (as with C structures). Member functions can also be called using the selection operators (see The keyword this). For example:

class X {
   int i;
   char name[20];
   X *ptr1;
   X *ptr2;
   void Xfunc(char*data, X* left, X* right);   // define elsewhere
void f(void);
   X x1, x2, *xptr=&x1;
   x1.i = 0;
   x2.i = x1.i;
   xptr->i = 1;
   x1.Xfunc("stan", &x2, xptr);

If m is a member or base member of class X, the expression X::m is called a qualified name; it has the same type as m, and it is an lvalue only if m is an lvalue. It is important to note that, even if the class name X is hidden by a non-type name, the qualified name X::m will access the correct class member, m.

Class members cannot be added to a class by another section of your program. The class X cannot contain objects of class X, but can contain pointers or references to objects of class X (note the similarity with C's structure and union types).

See Also

Personal tools
In other languages