C++ Program to illustrate classes and objects

We have already discussed the concept of classes and objects: https://techcpp.blogspot.in/2017/07/c-classes-and-objects.html.

Lets understand a simple program implementing that concept. The program below contains a class Box which can be used to create multiple boxes. The properties of Box are its Length, Width and Height. The member functions used are setDimensions() used to set length, width and height of the box and getVolume() used to obtain volume of the box. 

Two objects of this class is created in the main function and respective volumes are obtained by setting their dimensions.

PROGRAM

//Program to illustrate Object and classes

#include <iostream>

using namespace std;

class Box
{
        // Data Members

        float length;
        float width;
        float height;

        // Member Functions

        public:

        void setDimensions(float l, float w, float h)
        {
                length = l;
                width = w;
                height = h;
        }

        float getVolume()
        {
                return (length * width * height);
        }

};

int main()
{
        Box b1, b2;

        b1.setDimensions(10,20,30);
        cout<<"\nVOLUME OF BOX 1: "<<b1.getVolume();

        b2.setDimensions(5,25,15);
        cout<<"\nVOLUME OF BOX 2: "<<b2.getVolume();

        return 0;
}

OUTPUT

C++ Program to illustrate classes and objects


Share this

Related Posts

1 comments :

comments
November 12, 2018 at 6:26 PM delete

thank you for sharing useful post.
c++ programming tutorial
welookups

Reply
avatar

FIND US ON FACEBOOK!