Sunday, October 21, 2012

Setter & Getter in c++

  1. A property, is a special sort of class member; or intermediate between a field (or data member) and a method.
  2. Properties are read and written like fields, but property reads and writes are (usually) translated to get and set method calls.
  3. Property allows us data validation.

That is, properties are intermediate between member code (methods) and member data  (instance variables) of the class, and properties provide a higher level of encapsulation than public fields.

//property in c++

#include <iostream>
using namespace std;

class student
{
    public:
        void setName(string x)
        {
            name = x;
        }
        string getName()
        {
            return name;
        }
       
    private:
        string name;
};

int main()
{
    student bio_stud;


    bio_stud.setName("sir Virender");
    cout << bio_stud.getName();   
}


OUTPUT:
sir Virender


NOTE:
  1. C++ does not have first class properties, but there exist several ways to emulate properties to a limited degree.
  2. C++ require the programmer to define a pair of accessor and mutator methods.  
Further reading property and indexer in cpp

No comments:

Post a Comment