Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Implementing C# properties in C++

Status
Not open for further replies.

maluk

Programmer
Oct 12, 2002
79
SG
Here's a way you could implement C#'s property concept:

We want the public member variable INITIALIZED to be read-only. Here's how to implement it.

Code:
class A
{
  public:
      A() : INITIALIZED(initialized_)
      {
          initialized_ = 100;
      }

      void reconf(int i)
      {
          initialized_ = i;
      }
      const int& INITIALIZED; // read-only property
  private:
      int initialized_;
};

The [tt]INITIALIZED[/tt] member variable here is a read-only property that cannot be directly assigned to. It can only be assigned to by member functions.

Code:
int main(int argc, char* argv[])
{
    A a;

    cout << a.INITIALIZED << endl; // prints 100

    a.reconf(900);
    cout << a.INITIALIZED << endl; // prints 900

    a.INITIALIZED++; // oops! can't do this because it is read-only
    cout << a.INITIALIZED << " " << x << endl;

    return 0;
}

So there you have it!

Rome did not create a great empire by having meetings, they did it by
killing all those who opposed them.

- janvier -
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top