C++ class with setters-getters or accessors and mutators with functionality.

C++ class with setters-getters or accessors and mutators with functionality.

April 6, 2018
3 minutes read time
0 likes
0 comments
555 times viewed


header image

Description

Here we are going to look on the behavious of OOPs concepts in C++ using a Class called “Box”. We will also look on getting ahead with getters or accessors and then setters or mutators. We will also have some usecase funactionalty methods to achieve our tasks.

Content

Below is the complete code, I will explain the snippets later.

#include<bits/stdc++.h>
using namespace std;
#define fast ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)


class Box{
    private:
        int length;
        int width;
        int height;

    public:
        // Constructors
        Box() : length(0), width(0), height(0) {} // Default Constructor
        Box(int l, int w, int h): length(l), width(w), height(h) {} //Initialize the member variables to specific values


        // Getters or Accessers : const to avoid value change at time of get
        int getLength() const {
            return length;
        }
        int getWidth() const {
            return width;
        }
        int getHeight() const {
            return height;
        }


        // Setters or Mutators
        void setLength(int l){
            length = l;
        }
        void setWidth(int w){
            width = w;
        }
        void setHeight(int h){
            height = h;
        }


        // Check if empty
        bool empty(){
            if (length == 0 || width == 0 || height == 0)
                return true;
            return false;
        }


        // Calculate Volume
        int getVolume(int length, int width, int height){
            int volume = length * width * height;

            return volume;
        }


        // Print box dimension
        void print(int length, int width, int height){
            cout << "Length: " << length << " Width: " << width << " Height: " << height << endl;
        }


};





int main(){
    srand( time( 0 ) );
    fast;


    Box a(3, 2, 5), b;

    cout << "Box #1 : ";
    a.print(a.getLength(), a.getWidth(), a.getHeight());
    cout << "Volume: "<<a.getVolume(a.getLength(), a.getWidth(), a.getHeight())<<endl;


    b.setLength(5);
    b.setWidth(4);
    b.setHeight(7);

    cout << "Box #2 : ";
    b.print(b.getLength(), b.getWidth(), b.getHeight());
    cout <<"Volume: "<<b.getVolume(b.getLength(), b.getWidth(), b.getHeight())<<endl;

    return 0;

}


We are done



Like this post

0   Like


Share this post on

Google Plus LinkedIn


About the author




Join the discussion

Nothing to preview

Post Comment



Comments