Wednesday, December 7, 2011

Basic encapsulation (Accessing data through functions) Demo

//person_class.cpp

#include<iostream>
#include<string.h>
using namespace std;

class person
{
   // data members
   char name[30];  // Default access specifier is private
  int age;
  public:
   void getdata(void); //method declaration
  void display(void)//method declaration and definition
  {
  cout << endl <<"\t" << name ;
  cout << endl <<"\t" << age ;
  cout << endl <<"\t" << pid ;
  }
  private:
   int pid;
   public: void setdata(char[],int,int);
};

void person::getdata(void)
{
  cout <<"Enter name : ";
  cin>> name;
  cout <<"Enter age : ";
  cin>> age;
  cout <<"Enter pid : ";
  cin>> pid;
}

void person::setdata(char n[],int a,int p)
{
   strcpy(name,n);
   age = a;
   pid = p;
}
main()
{
   person raj,yash;
   raj.setdata((char*)"raj",20,101);

   yash.getdata();

   raj.display();
   yash.display();

   return 0;
}

No comments:

Post a Comment