+92 332 4229 857 99ProjectIdeas@Gmail.com

Encapsulation (C++)


Ensapculation
Encapsulation is a technique which is used to hide the data. In object oriented programming (classes) encapsulation is achieved by declaring the attributes of a class as private so that they cannot be accessed outside the class except through getters or setter which are public functions of that class.Below mentioned example gives a complete overview on encapsulation.


Example

#include "stdafx.h"

#include "iostream"

#include "conio.h"


using namespace std;


// EMPLOYEE CLASS, AN EMPLOYEE IS DEFINED IN TERMS

// OF ITS ATTRIBUTES I.E ID, NAME, AGE ETC

class Employee

{

// ATTRIBUTES OF AN EMPLOYEE

// THESE ARE DECLARED AS PRIVATE FOR ENCAPSULATION

private:

            int id;

            char*name;

            int age;

public:

// ALL FUNCTIONS OF AN EMPLOYEE CLASS

            Employee();

            Employee(int,char*,int);

            void setId(int);

            void setName(char*);

            void setAge(int);

            int getId();

            char*getName();

            int getAge();

            void display();

};


// CONSTRUCTOR # 1 WITH NO PARAMETERS

Employee::Employee()

{


}


// CONSTRUCTOR # 2 WITH PARAMETERS

Employee::Employee(int _id , char * _name , int _age)

{

            setId(_id);

            setName(_name);

            setAge(_age);

}


// ID SETTER FUNCTION

void Employee::setId(int _id)

{

            id = _id ;

}


// NAME SETTER FUNCTION

void Employee::setName(char * _name)

{

            name = new char[ strlen ( _name ) + 1];

            name = _name ;

}


// AGE SETTER FUNCTION

void Employee::setAge(int _age)

{

            age = _age ;

}


// ID GETTER FUNCTION

int Employee::getId()

{

            return id;

}


// NAME GETTER FUNCTION

char * Employee::getName()

{

            return name;

}


// AGE GETTER FUNCTION

int Employee::getAge()

{

            return age;

}


// FUNCTION FOR DISPLAYING THE ATTRIBUTES OF A PARTICULAR EMPLOYEE

void Employee::display()

{

            cout << "Employee ID       > " << getId() << endl ;

            cout << "Employee Name > " << getName() << endl ;

            cout << "Employee Age    > " << getAge() << endl ;

}


// DRIVER FUNCTION

int main()

{

            Employee E1(1,"Saad Bin Saulat",21);

            E1.display();

            Employee E2(2,"Osama Shaukat",22);

            E2.display();

            Employee E3(3,"Ayesha Khan",20);

            E3.display();


            _getche();

            return 0;

}

Output

Employee ID         > 1

Employee Name   > Saad Bin Saulat

Employee Age      > 21

Employee ID         > 2

Employee Name   > Osama Shaukat

Employee Age      > 22

Employee ID         > 3

Employee Name   > Ayesha Khan

Employee Age      > 20

0 comments: