How to define and how to use properties in Visual C++ (815703)



The information in this article applies to:

  • Microsoft Visual C++ 2005 Express Edition
  • Microsoft Visual C++ .NET (2003)
  • Microsoft Visual C++ .NET (2002)

SUMMARY

This step-by-step article describes how to define and how to use properties in a Microsoft Visual C++ .NET or Microsoft Visual C++ 2005 application.

One important aim of many object-oriented programming languages is to permit you to encapsulate internal details in a class. Visual C++ .NET or Visual C++ 2005 permits you to define properties to provide controlled access to internal details in a class.

A property can be read-only, write-only, or read/write. A get accessor provides read access. A set accessor provides write access. You can add code to these accessors to provide the appropriate functionality to access or set the property.

In this article, you create a class that is named Employee. After you define the following properties for the Employee class, you create an Employee object and use its properties:
  • A read/write property for the name of the employee
  • A property to read the salary of the employee
  • A property to calculate how long the employee has worked for the company
back to the top

Requirements

The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
  • Microsoft Visual Studio .NET
  • Microsoft Visual Studio 2005
This article assumes that you are familiar with the following topics:
  • Visual C++ .NET or Visual C++ 2005 syntax
  • Object-oriented concepts
back to the top

Create an application that contains a Visual C++ class

  1. Start Visual Studio .NET or Visual Studio 2005.
  2. On the File menu, point to New, and then click Project.
  3. Select a new project template in your version of Visual C++:
    1. In Visual C++ .NET 2002, click Visual C++ Projects under Project Types, and then click Managed C++ Application under Templates.
    2. In Visual C++ .NET 2003, click Visual C++ Projects under Project Types, and then click Console Application (.NET) under Templates.
    3. In Visual C++ 2005, click Visual C++ under Project Types, and then click CLR Console Application under Templates.
  4. In the Name text box, type EmployeeProperties.
  5. In the Location text box, type C:\Test, and then click OK.

    By default, EmployeeProperties.cpp is created.
  6. On the Project menu, click Add Class.
  7. In the Add Class dialog box, select Generic C++ Class under Templates, and then click Open.
  8. In the Generic C++ Class Wizard, type Employee in the Class name text box, and then click Finish. The Employee class appears as follows:
    #pragma once
    
    class Employee
    {
    public:
    	Employee(void);
    	~Employee(void);
    };
    To make the Employee class a Managed Extensions for C++ class, add the __gc keyword before the Employee class:
    #pragma once
    
    __gc class Employee
    {
    public:
    	Employee(void);
    	~Employee(void);
    };
    Note In Visual C++ .NET 2002, move the following statement:
    #include "Employee.h"
    Move the previous statement to appear after the following statement in the Employee.cpp file:
    #using <mscorlib.dll>
back to the top

Define fields, constructors, and methods

  1. Use the using directive on the System namespace so that you do not have to qualify declarations from these namespaces later in your code. Add the following code in the Employee.h file:
    using namespace System; // This shortcut avoids you having to type System::Console and System::String
  2. Add three Private fields to the Employee class, as follows:
    private:
    	String *m_name;
    	float m_salary;
    	DateTime m_hireDate;
  3. Define a constructor for the class to initialize the fields in the Employee class, as follows:
    public:
    Employee(String *name, float salary, DateTime hireDate)
    {
    	this->m_name = name;
    	this->m_salary = salary;
    	this->m_hireDate = hireDate;
    }
    
    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.
  4. Add a Public method to the class, as follows:
    public:
    void PayRise(float amount)
    {
    	this->m_salary += amount;
    }
back to the top

Define the properties in the class

  1. Add the following code to add a read/write property that is named FullName.
    • The get accessor returns the name of the employee.
    • The set accessor uses an implicit parameter that is named value and that is passed in the set accessor to set the name of the employee.
    __property String* get_FullName() 
    { 
    	return m_name; 
    }
    __property void set_FullName(String* value) 
    { 
    	m_name = value; 
    }
    
  2. Add the following code to add a read-only property that is named Remuneration.
    • The get accessor returns the salary of the employee.
    • No set accessor exists because the salary cannot be set directly; the only way to change the salary is to call the PayRise method.
    __property float get_Remuneration() 
    { 
    	return m_salary; 
    }
  3. Add the following code to add another read-only property that is named DaysSinceJoined. The get accessor calculates how many days the employee has worked for the company.
    __property int get_DaysSinceJoined()
    {
    	TimeSpan timeSpan = DateTime::Now.Subtract(m_hireDate);
    	return timeSpan.Days;
    }
back to the top

Create an object and use the properties

  1. In Solution Explorer, open the EmployeeProperties.cpp file, and then add the following code to the EmployeeProperties.cpp file:
    #include "Employee.h"
  2. In the _tmain function, use the new operator to create an Employee object. Assign the object reference to a local Employee variable, as follows:
    Employee *worker = new Employee("Jayne Doe", 12500, DateTime(1998, 7, 31));
  3. Add the following code to change the FullName property of the employee. This implicitly invokes the set accessor for the FullName property:
    worker->FullName = "Jayne Lafayette";
  4. Add the following code to display the employee details by using the get accessors for the FullName property, the Remuneration property, and the DaysSinceJoined property:
    Console::WriteLine("Full name: {0}", worker->get_FullName());
    Console::WriteLine("Remuneration: {0}", __box(worker->get_Remuneration()));
    Console::WriteLine("Days since joined: {0}", __box(worker->get_DaysSinceJoined()));
back to the top

Test the application

  1. Build and run the application.
  2. The application displays the following information in the console (the value of the Days since joined attribute depends on the current date):
    Full name: Jayne Lafayette
    Remuneration: 125000
    Days since joined: 1139
    
  3. Return to the EmployeeProperties.cpp file in the Code View window, and then add the following code at the end of the _tmain function:
    worker->Remuneration = 100000;
  4. Try to build the application. You receive a compilation error because Remuneration is a read-only property.
  5. Change the statement as follows:
    worker->m_salary = 100000;
  6. Try to build the application again.

    You receive another compilation error because the Salary field is marked as Private. The only way to modify the salary of the employee is to use the public PayRise method.
back to the top

Modification Type:MajorLast Reviewed:1/5/2006
Keywords:kbManaged kbProperties kbConsole kbHOWTOmaster kbhowto KB815703 kbAudDeveloper