OBJECTS

When the class is formed , a number of objects may be created from the class as objects are illustration of the class .Objects are the physical entity to represent classes .A class gives you the blueprints for objects , thus generally an object is formed from a class . We declare objects of a class with precisely the same kind of declaration that we declare variables of fundamental types .


Syntax for declaring an object:


class_name object_name;


Let us assume we have created a class aman, ankit. Then creating objects for these two classes will be like:

aman a;         //object a is created
ankit b;          //object b is created

Note that you can only access the members of a class just after creating an object for that class.


Accessing data members of a class after creating an object:


The public data members of objects of a class can be accessed using the direct member access operator (.).

However,private and protected members can not be accessed directly using direct member access operator (.). 
For eg.


#include <iostream>

using namespace std;


// Program for finding the volume of a cuboid

class Cuboid
{
   public:
      double l;   // length of a Cuboid
      double b;  // Breadth of a Cuboid
      double h;   // Height of a Cuboid
};

int main( )

{
   Cuboid Cuboid1;        // Declare Cuboid1 of type Cuboid
   Cuboid Cuboid2;        // Declare Cuboid2 of type Cuboid
   double vol = 0.0;     // Store the volume of a Cuboid here

   // Cuboid 1 specification

   Cuboid1.h = 5.0; 
   Cuboid1.l = 6.0; 
   Cuboid1.b = 7.0;

   // Cuboid 2 specification

   Cuboid2.h = 10.0;
   Cuboid2.l = 12.0;
   Cuboid2.b = 13.0;
   // volume of Cuboid 1
   vol = Cuboid1.h * Cuboid1.l * Cuboid1.b;
   cout << "vol of Cuboid1 : " << vol <<endl;

   // volume of Cuboid 2

   vol = Cuboid2.h * Cuboid2.l * Cuboid2.b;
   cout << "vol of Cuboid2 : " << vol <<endl;
   return 0;
}

As all the data mebers are public hence these are accessed directly in the program.If we have used private for that then there will be error while using them in the main program.In case of protected, we can access those data members within the same package


Example using private access identifier:



#include <iostream>

using namespace std;


// Program for finding the volume of a cuboid

class Cuboid
{
   private:
      double l;   // length of a Cuboid
      double b;  // Breadth of a Cuboid
      double h;   // Height of a Cuboid

public:

    float vol(l,b,h)
    {
   double vol;
    vol = l*b*h;
   return 0;
   }
};

int main( )

{
   Cuboid Cuboid1;        // Declare Cuboid1 of type Cuboid
   Cuboid Cuboid2;        // Declare Cuboid2 of type Cuboid
   double m,n;
   m=Cuboid1.vol(20,10,12);
   n=Cuboid2.vol(10,10,13);
   cout << "vol of Cuboid1 : " <<m<<endl;
   cout << "vol of Cuboid2 : " <<n <<endl;
   return 0;
}



0 comments to "CLASSES AND OBJECTS(cont.)"

Post a Comment

Powered by Blogger.