How to create and use static members by using Visual C++ (815704)
The information in this article applies to:
- Microsoft Visual C++ 2005 Express Edition
- Microsoft Visual C++ .NET (2003)
- Microsoft Visual C++ .NET (2002)
- 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:
IN THIS TASKINTRODUCTIONThis 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 topRequirementsThis 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 topCreate a Visual C++ project and classThe 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. - In the Class name box, type
NewClass, and then click
Finish.
- 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.
- 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;
- Add the __gc keyword before the NewClass definition to make the NewClass a Managed Extensions for C++ class.
__gc class NewClass - Add two private instance member variables after the NewClass destructor function.
//Instance variables
private:
int myInt;
String * myStr; - Use the static keyword to add two private static member variables.
//Class variables
private:
static int staticInt;
static String * staticPropValue; - Press the CTRL+SHIFT+S key combination to save the
project.
Back to the topCreate the Instance
method, Static method, and Static property- 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
} - 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
} - 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
} - Press the CTRL+SHIFT+S key combination to save the
project.
Back to the topCompile the
class- 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. - 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. - 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. - Press the CTRL+SHIFT+B key combination to build the
solution
Back to the topCreate the test
program- Open the file in the code editor. To do this, double-click
StaticMethod.cpp, under Source Files in Solution Explorer.
- Add the following include statement before the
_tmain function in the code window.
#include "NewClass.h" - 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); - 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:
- Click Project, and then click <ProjectName> Properties.
Note <ProjectName> is a placeholder for the name of the project. - Expand Configuration Properties, and then click General.
- 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:These steps apply to the whole article.
- Press the CTRL+SHIFT+S key combination to save the
project.
Back to the topCompile the test
program- 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. - 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.
- Click No in the Just-In-Time
Debugging dialog box, and then press ENTER to
return to the source code.
- 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; - To create an instantiated object, modify this code
as follows.
NewClass * MyObject = new NewClass(); - Press the CTRL+SHIFT+S key combination to save the
project.
- Press the CTRL+SHIFT+B key combination to build the
solution.
- Press the CTRL+F5 key combination to run the
project.
Back to the topTroubleshooting- 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
topREFERENCESFor more information about static variables and static
member functions, visit the following Microsoft Developer Network (MSDN) Web
sites: Back to the top
Modification Type: | Major | Last Reviewed: | 1/5/2006 |
---|
Keywords: | kbManaged kbLangCPP kbProperties kbProgramming kbConsole kbHOWTOmaster KB815704 kbAudDeveloper |
---|
|
|
©2004 Microsoft Corporation. All rights reserved.
|
|