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

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

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.
  1. Start Microsoft Visual Studio .NET or Microsoft Visual Studio 2005.
  2. On the File menu, point to
    New, and then click Project.
  3. 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.
  4. In the Name box, type
    StaticMethod, and then click
    OK.
  5. On the Project menu, click Add Class.
  6. 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.
  7. In the Class name box, type
    NewClass, and then click
    Finish.
  8. 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.
  9. Add the following code in the NewClass.h file after the
    #pragma directive.
    #using <mscorlib.dll>// This line is required only for VS .NET 2002
    using namespace System;
  10. Add the __gc keyword before the NewClass definition to make the NewClass a Managed Extensions for C++ class.
    __gc class NewClass
  11. Add two private instance member variables after the NewClass destructor function.
    //Instance variables
    private:
    int myInt;
    String * myStr;
  12. Use the static keyword to add two private static member variables.
    //Class variables
    private:
    static int staticInt;
    static String * staticPropValue;
  13. Press the CTRL+SHIFT+S key combination to save the project.
Back to the top

Create the Instance method, Static method, and Static property

  1. 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
    }
  2. 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
    }
  3. 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
    }
  4. Press the CTRL+SHIFT+S key combination to save the project.
Back to the top

Compile the class

  1. 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.
  2. 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.
  3. 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.
  4. Press the CTRL+SHIFT+B key combination to build the solution
Back to the top

Create the test program

  1. Open the file in the code editor. To do this, double-click
    StaticMethod.cpp, under Source Files in Solution Explorer.
  2. Add the following include statement before the
    _tmain function in the code window.
    #include "NewClass.h"
  3. Add the following code that uses the class name to reference NewClass members, to the beginning of _tmain function.
    String * outStr;

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

    Console::WriteLine(outStr);
  4. 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"Obj Ref" ; // 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:

    1. Click Project, and then click <ProjectName> Properties.



      Note <ProjectName> is a placeholder for the name of the project.
    2. Expand Configuration Properties, and then click General.

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

    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.
  5. Press the CTRL+SHIFT+S key combination to save the project.
Back to the top

Compile the test program

  1. 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.
  2. 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 "System.NullReferenceException" error.
  3. Click No in the Just-In-Time Debugging dialog box, and then press ENTER to return to the source code.
  4. 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;
  5. To create an instantiated object, modify this code as follows.
    NewClass * MyObject = new NewClass();
  6. Press the CTRL+SHIFT+S key combination to save the project.
  7. Press the CTRL+SHIFT+B key combination to build the solution.
  8. Press the CTRL+F5 key combination to run the project.
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

References

For more information about static variables and static member functions, visit the following Microsoft Developer Network (MSDN) Web sites:Back to the top
Egenskaper

Artikel-id: 815704 – senaste granskning 7 dec. 2007 – revision: 1

Feedback