Sunday, July 23, 2017

C++ program to access Data Members of a class.

This C++ program will demonstrate how to access the Data Members of a class.

#include <iostream>
using namespace std;

class Box {
   public:
      double length;   
      double breadth;  
      double height;   
};

int main( ) {
   Box MyBox;        
   double volume; //for storing volumne of box

   // MyBox initialization
   MyBox.height = 2; 
   MyBox.length = 3; 
   MyBox.breadth = 5;
   
   /* Note: public data members of objects of a class 
   can be accessed using direct member access operator "." 
   */

   // volume of MyBox
   volume = MyBox.height * MyBox.length * MyBox.breadth;
   cout << "Volume of MyBox = " << volume <<endl;

   return 0;
}

Output of program

Volume of MyBox : 30

No comments:

Post a Comment