find volume of a box using object oriented programming with c++

Viewed 3191

Write a class called boxVolume with length, width and height as data members and readData(), dispData() and computeVol() as functions. Also write a main() function to test the boxVolume class.

i tried -

#include <iostream>

class BoxVolume
{
    public:

    float length;
    float width;
    float height;

    void readData()
    {
        using namespace std
        cout << "length: ";
        cin >> 'BoxVolume::length';
        cout << "width: ";
        cin >> 'BoxVolume::width';
        cout << "height: ";
        cin >> 'BoxVolume::height';
    }
    void computeVolume()
    {
        float volume;
        volume = 'void readData()::length' * 'void readData()::width' * 'void readData()::height';
    }

    void dispData()
    {
        using namespace std
        cout << "Volume is:" << 'void computeVolume()::volume';

    }

};

int main()
{
    BoxVolume obj1,obj2,obj3;
    obj1.readData();
    obj2.computeVolume();
    obj3.dispData();

};
1 Answers

You should read a C++ introductory book to acquire the basics of the language first, and then start coding. I would suggest Accelerated C++ because is shorter than its competitors but still quite complete (at the time it was published). Now it lacks support for subsequent standards in the language, from C++11 onward, so at the moment C++ Primer may be the best pick, although is about 1000 pages and a new edition is poised to come out in a few months. Alternatively, there is Stroustrup's A tour of C++. He is the creator of the language.

A compiling version of your code below, I have added encapsulation but if you don't care about making your data members public you can use a struct in place of a class:

#include <iostream>

using namespace std;

class BoxVolume
{
public:
    void readData()
    {
        cout << "length: ";
        cin >> length;
        cout << "width: ";
        cin >> width;
        cout << "height: ";
        cin >> height;
    }

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

    void dispData()
    {
        //using namespace std  // this is artistic I couldnt cancel it
        cout << "Volume is: " << computeVolume() << endl;

    }

private:
    float length;
    float width;
    float height;
};

int main()
{
    BoxVolume obj1,obj2,obj3;
    obj1.readData();
    obj2.computeVolume();  // data undefined for obj2
    obj3.dispData();       // data undefined for obj3
};

Yes I couldn't resist answering this.

Related