Implementation of Object Oriented Programming

Note: For compiling programs use http://cpp.sh/

class in C++ is a user defined type or data structure declared with keyword class that has data and functions (also called methods) as its members whose access is governed by the three access specifiers private, protected or public (by default access to members of a class is private).

A member function of a class is a function that has its definition or its prototype within the class definition like any other variable. It operates on any object of the class of which it is a member, and has access to all the members of a class for that object. Member functions can be defined within the class definition or separately using scope resolution operator, : −. Defining a member function within the class definition declares the function inline, even if you do not use the inline specifier. So either you can define Volume() function as below –

class Box {

   public:

      double length;      // Length of a box

      double breadth;     // Breadth of a box

      double height;      // Height of a box

  

      double getVolume(void) {

         return length * breadth * height;

      }

};

If you like, you can define the same function outside the class using the scope resolution operator (::) as follows −

double Box::getVolume(void) {

   return length * breadth * height;

}

Here, only important point is that you would have to use class name just before :: operator. A member function will be called using a dot operator (.) on a object where it will manipulate data related to that object only as follows −

Box myBox;          // Create an object

 

myBox.getVolume();  // Call member function for the object

Let us put above concepts to set and get the value of different class members in a class –

 

 

 

#include <iostream>

 

using namespace std;

 

class Box {

   public:

      double length;         // Length of a box

      double breadth;        // Breadth of a box

      double height;         // Height of a box

 

      // Member functions declaration

      double getVolume(void);

      void setLength( double len );

      void setBreadth( double bre );

      void setHeight( double hei );

};

 

// Member functions definitions

double Box::getVolume(void) {

   return length * breadth * height;

}

 

void Box::setLength( double len ) {

   length = len;

}

void Box::setBreadth( double bre ) {

   breadth = bre;

}

void Box::setHeight( double hei ) {

   height = hei;

}

 

// Main function for the program

int main() {

   Box Box1;                // Declare Box1 of type Box

   Box Box2;                // Declare Box2 of type Box

   double volume = 0.0;     // Store the volume of a box here

 

   // box 1 specification

   Box1.setLength(6.0);

   Box1.setBreadth(7.0);

   Box1.setHeight(5.0);

 

   // box 2 specification

   Box2.setLength(12.0);

   Box2.setBreadth(13.0);

   Box2.setHeight(10.0);

 

   // volume of box 1

   volume = Box1.getVolume();

   cout << "Volume of Box1 : " << volume <<endl;

 

   // volume of box 2

   volume = Box2.getVolume();

   cout << "Volume of Box2 : " << volume <<endl;

   return 0;

}

 

run

Output-

Volume of Box1 : 210
Volume of Box2 : 1560

 

Access Control in Classes

Access specifiers in C++ class defines the access control rules. C++ has 3 new keywords introduced, namely,

1.     public

2.     private

3.     protected

These access specifiers are used to set boundaries for availability of members of class be it data members or member functions

Access specifiers in the program, are followed by a colon. You can use either one, two or all 3 specifiers in the same class to set different boundaries for different class members. They change the boundary for all the declarations that follow them.


Public

Public, means all the class members declared under public will be available to everyone. The data members and member functions declared public can be accessed by other classes too. Hence there are chances that they might change them. So the key members must not be declared public.

Class PublicAccess

{

 public:   // public access specifier

 int x;            // Data Member Declaration

 void display();   // Member Function decaration

}

 

 


Private

Private keyword, means that no one can access the class members declared private outside that class. If someone tries to access the private member, they will get a compile time error. By default class variables and member functions are private.

class PrivateAccess

{

 private:   // private access specifier

 int x;            // Data Member Declaration

 void display();   // Member Function decaration

}

 

 

 

Protected

Protected, is the last access specifier, and it is similar to private, it makes class member inaccessible outside the class. But they can be accessed by any subclass of that class. (If class A is inherited by class B, then class B is subclass of class A. We will learn this later.)

class ProtectedAccess

{

 protected:   // protected access specifier

 int x;            // Data Member Declaration

 void display();   // Member Function decaration

}

 

 

 

Accessing Data Members of Class

Accessing a data member depends solely on the access control of that data member. If its public, then the data member can be easily accessed using the direct member access (.) operator with the object of that class.

If, the data member is defined as private or protected, then we cannot access the data variables directly. Then we will have to create special public member functions to access, use or initialize the private and protected data members. These member functions are also called Accessors and Mutator methods or getter and setter functions.


Accessing Public Data Members

Following is an example to show you how to initialize and use the public data members using the dot (.) operator and the respective object of class.

class Student

{

 public:

 int rollno;

 string name;

};

 

int main()

{

 Student A;

 Student B;

 A.rollno=1;

 A.name="Adam";

 

 B.rollno=2;

 B.name="Bella";

 

 cout <<"Name and Roll no of A is :"<< A.name << A.rollno;

 cout <<"Name and Roll no of B is :"<< B.name << B.rollno;

}

 

 

 


Accessing Private Data Members

To access, use and initialize the private data member you need to create getter and setter functions, to get and set the value of the data member.

The setter function will set the value passed as argument to the private data member, and the getter function will return the value of the private data member to be used. Both getter and setter function must be defined public.

class Student

{

 private:    // private data member

 int rollno;

 

 public:     // public accessor and mutator functions

 int getRollno()

 {

  return rollno;

 }

 

 void setRollno(int i)

 {

  rollno=i;

 }

 

};

 

int main()

{

 Student A;

 A.rollono=1;  //Compile time error

 cout<< A.rollno; //Compile time error

 

 A.setRollno(1);  //Rollno initialized to 1

 cout<< A.getRollno(); //Output will be 1

}

 

 

Example :

 

 

 

So this is how we access and use the private data members of any class using the getter and setter methods. We will discuss this in more details later.


 

 

 

Accessing Protected Data Members

Protected data members, can be accessed directly using dot (.) operator inside the subclass of the current class, for non-subclass we will have to follow the steps same as to access private data member.

 Passing Objects as Function arguments

                           Example # 1

#include <iostream>

using namespace std;

class rational

{

private:

            int num;

            int dnum;

public:

            rational():num(1),dnum(1)

            {}

            void get ()

            {

                        cout<<"enter numerator";

                        cin>>num;

                        cout<<"enter denomenator";

                        cin>>dnum;

            }

            void print ()

            {

                        cout<<num<<"/"<<dnum<<endl;

            }

            void multi(rational r1,rational r2)

            {

                        num=r1.num*r2.num;

                        dnum=r1.dnum*r2.dnum;

            }

};

void main ()

{

            rational r1,r2,r3;

            r1.get();

            r2.get();

            r3.multi(r1,r2);

 

            r3.print();

           

run}