Microsoft KB Archive/815704

= How to create and use static members by using Visual C++ =

Article ID: 815704

Article Last Modified on 5/13/2007

-

APPLIES TO


 * Microsoft Visual C++ 2005 Express Edition
 * Microsoft Visual C++ .NET 2003 Standard Edition
 * Microsoft Visual C++ .NET 2002 Standard Edition
 * Microsoft .NET Framework 1.1
 * Microsoft .NET Framework 1.0

-







For a Microsoft Visual Basic .NET version of this article, see 308371.



For a Microsoft Visual C# .NET version of this article, see 815705.

This article refers to the following Microsoft .NET Framework Class Library namespaces:
 * System

IN THIS TASK

 * INTRODUCTION
 * Requirements
 * Create a Visual C++ .NET project and class
 * Create the Instance method, Static method, and Static property
 * Compile the class
 * Create the test program
 * Compile the test program
 * Troubleshooting
 * REFERENCES



INTRODUCTION
This article describes how to implement static members in a class and also how to reference other class members from static methods and static properties.

You can do this in Microsoft Visual C++ .NET or in Microsoft Visual C++ 2005 with classes. Classes implement their functionality by using functions, properties, and fields that are named class members.

Static members are named shared or class members in Microsoft Visual Basic .NET and in Microsoft Visual C# .NET. Static members are not associated with a specific instance of a class. Therefore, these class members are shared by all objects that are instantiated from that class. To call a static member, you can qualify it with the class name or with an object of that class. Because static members are not associated with object instances, they do not have access to non-static members. Non-static members are accessed through the this object and represent the current object instance.

Non-static members are named instance members because they are associated with individual object instances. Static members belong to the class, and instance members belong to instances (or objects) of the class.

Back to the top

Requirements
This article assumes that you are familiar with the following topics:
 * Object-oriented concepts
 * Creating classes in Visual C++ .NET or in Visual C++ 2005
 * Visual C++ .NET properties or Visual C++ 2005 properties

Back to the top

Create a Visual C++ project and class
The code in this project describes how to implement static methods, static properties, and instance methods. Some of the following code contains deliberate errors to illustrate key points about how to access other members from static members. Therefore, the code compiles only after you comment out or remove the lines that cause the error.  Start Microsoft Visual Studio .NET or Microsoft Visual Studio 2005. On the File menu, point to New, and then click Project. In Visual Studio .NET 2002, click Visual C++ Projects under Project Types, and then click Managed C++ Application under Templates.

In Visual Studio .NET 2003, click Visual C++ Projects under Project Types, and then click Console Application (.NET) under Templates.

In Visual Studio 2005, click Visual C++ under Project Types, and then click CLR Console Application under Templates. In the Name box, type StaticMethod, and then click OK. On the Project menu, click Add Class. In the Add Class - StaticMethod dialog box, click Generic C++ Class under Templates, and then click Open.

Note In Visual Studio 2005, Generic C++ Class is changed to C++ Class.</li> In the Class name box, type NewClass, and then click Finish.</li> Open the file in the code window if it is not already open. To do this, double-click NewClass.h under Header Files in Solution Explorer.</li>  Add the following code in the NewClass.h file after the #pragma directive. using namespace System; </li>  Add the __gc keyword before the NewClass definition to make the NewClass a Managed Extensions for C++ class. __gc class NewClass </li>  Add two private instance member variables after the NewClass destructor function. //Instance variables private: int myInt; String * myStr; </li>  Use the static keyword to add two private static member variables. //Class variables private: static int staticInt; static String * staticPropValue; </li> Press the CTRL+SHIFT+S key combination to save the project.</li></ol>
 * 1) using <mscorlib.dll>// This line is required only for VS .NET 2002

Back to the top

Create the Instance method, Static method, and Static property
<ol>  Add the following instance method that is named mySub to the NewClass class. public: //An instance method void mySub {       myInt = 1;       // Ok, same as this->myInt = 1 staticInt = 1;  // Ok, same as NewClass->staticInt = 1 } </li>  Use the static keyword to add the following static method that is named staticSub. Remember that static methods can only access other static members and not instance members. //A class method static void staticSub {       myInt = 1;       // Error, cannot access this->myInt staticInt = 1;  // Ok, same as NewClass->staticInt = 1 } </li>  Add a static property getter function and a static property setter function (read/write property) for the staticPropValue member. //A class property __property static String* get_StaticPropValue {   //can only refer to static variables return myStr;           // Error, cannot access NewClas->myStr return staticPropValue; // Ok, same as Return NewClas->staticPropValue } __property static void set_StaticPropValue(String * Value) {   //can only refer to static variables myStr = Value;          // Error, cannot access this->myStr staticPropValue = Value; // Ok, same as NewClas.staticPropValue = Value } </li> Press the CTRL+SHIFT+S key combination to save the project.</li></ol>

Back to the top

Compile the class
<ol>  Press the CTRL+SHIFT+B key combination to build the solution. Notice that you receive three error messages in the Task List window.

The first error occurs at the following line of code in the staticSub method. myInt = 1;      // Error, cannot access this->myInt Because staticSub is a static method, it is associated with the class and can only access static members. You cannot use the this keyword here because instance members are not accessible from a static member. Remove this line of code. </li>  The second error occurs at the following line of code in the get_StaticPropValue property getter function. return myStr; // Error, cannot access NewClass->myStr Remove this line of code. </li>  The third error occurs at the following line of code in the set_StaticPropValue property setter function. myStr = Value;     // Error, cannot access NewClass->myStr Remove this line of code. </li> Press the CTRL+SHIFT+B key combination to build the solution</li></ol>

Back to the top

Create the test program
<ol> <li>Open the file in the code editor. To do this, double-click StaticMethod.cpp, under Source Files in Solution Explorer.</li> <li> Add the following include statement before the _tmain function in the code window. <li> Add the following code that uses the class name to reference NewClass members, to the beginning of _tmain function. String * outStr;
 * 1) include &quot;NewClass.h&quot; </li>

// Use class to refer to members NewClass::staticSub;                         // Ok NewClass::StaticPropValue = S&quot;New Class&quot;;       // Ok outStr = NewClass::get_StaticPropValue;       // Ok NewClass::mySub;                              // Error only available to an instance

Console::WriteLine(outStr); </li> <li> Add the following code that uses an object reference to reference the NewClass members. // Use an object reference to refer to members NewClass * MyObject; MyObject->staticSub;                      // Ok MyObject->StaticPropValue = S&quot;Obj Ref&quot; ;    // Ok outStr = MyObject->get_StaticPropValue;   // Ok MyObject->mySub;                           // This will fail at runtime as MyObject is Not instantiated

Console::WriteLine(outStr); Note You must add the common language runtime support compiler option (/clr:oldSyntax) in Visual C++ 2005 to successfully compile the previous code sample. To add the common language runtime support compiler option in Visual C++ 2005, follow these steps: <ol style="list-style-type: lower-alpha;"> <li>Click Project, and then click  Properties.

Note  is a placeholder for the name of the project.</li> <li>Expand Configuration Properties, and then click General.</li> <li>Click to select Common Language Runtime Support, Old Syntax (/clr:oldSyntax) in the Common Language Runtime support project setting in the right pane, click Apply, and then click OK.</li></ol>

For more information about the common language runtime support compiler option, visit the following Microsoft Web site:

/clr (Common Language Runtime Compilation)

http://msdn2.microsoft.com/en-us/library/k8d11d4s.aspx

These steps apply to the whole article. </li> <li>Press the CTRL+SHIFT+S key combination to save the project.</li></ol>

Back to the top

Compile the test program
<ol> <li> Press the CTRL+SHIFT+B key combination to build the solution. Notice that you receive an error message in the Task List window. This error occurs in the following line of code. NewClass::mySub; // Error only available to an instance mysub is an instance method and therefore is only available to an instance of a NewClass object. Remove this line of code. </li> <li>Click Start Without Debugging on the Debug menu to run the program outside the debugger. Notice that the Just-In-Time (JIT) debugger displays the &quot;System.NullReferenceException&quot; error.</li> <li>Click No in the Just-In-Time Debugging dialog box, and then press ENTER to return to the source code.</li> <li> This exception occurs because the following line of code creates an object reference instead of the instantiated object that you must have to invoke an instance method. NewClass * MyObject; </li> <li> To create an instantiated object, modify this code as follows. NewClass * MyObject = new NewClass; </li> <li>Press the CTRL+SHIFT+S key combination to save the project.</li> <li>Press the CTRL+SHIFT+B key combination to build the solution.</li> <li>Press the CTRL+F5 key combination to run the project.</li></ol>

Back to the top

Troubleshooting

 * You can only invoke instance methods and properties on an object instance. In the instance method, you can reference both instance and static members.
 * To invoke static members, you can use the class itself, an object reference, or an object instance. In the static member, you can only reference other static members.
 * You cannot refer to an instance member of a class from a static method or from a static member initializer without an explicit instance of the class. Accessing the member by using the this object is valid only from an instance method.

Back to the top

<div class="references_section">