Answer to Question #252182 in C++ for Muhammad Haris

Question #252182

Write a definition of a distance class as shown in the example 4.2 above. Make all the appropriate function constant. Include a constant data member called id of integer type. Create two object constant and non-constant. Assign values and display them. Also check what happens  If you try to modify private data member of an object from the definition of const function   If you try to modify the private data member of const object from the definition of non-constant function. 


1
Expert's answer
2021-10-17T01:45:22-0400
#include <iostream>


using namespace std;


class Distance{
    private:
        int feet;
        float inches;
        const int id=0;
    public:
        Distance(){
            cout<<"default constructor"<<endl;
            feet=0;inches=0;
        }
        Distance(float mtrs){
            cout<<"one argument constructor"<<endl;
            float ft=mtrs*3.28084;
            feet=(int)ft;
            inches=(ft-feet)*12;
        }
        Distance(int f, float i){
            cout<<"two argument constructor"<<endl;
            feet=f;inches=i;
        }
        void setdist(int ft, float in){
            feet=ft;
            inches=in;
        }
        void getdist(){
            cout<<"\nEnter feet: "; cin>>feet;
            cout<<"\nEnter inches: ";cin>>inches;
        }
        void initialize(){
            feet=0;
            inches=0;
        }
        void showdist(){
            cout<<"feet= "<<feet<<"\t inches= "<<inches<<"\nid= "<<id<<endl;
        }
        
};
int main()
{
    Distance dist1, dist2;
    dist1.setdist(11,625);
    Distance dist3(3,5.75);
    Distance dist4(1);
    cout<<"dist1: ";dist1.showdist();
    cout<<"dist2: ";dist2.showdist();
    cout<<"dist3: ";dist3.showdist();
    cout<<"dist4: ";dist4.showdist();
    const Distance d1; 
    const Distance d2;
    Distance d3; 
    Distance d4;
    d1.setdist(11,625);
    d2.setdist(12,626);
    d3.setdist(13,627);
    d4.setdist(14,628);
    cout<<"d1: ";d1.showdist();
    cout<<"d2: ";d2.showdist();
    cout<<"d3: ";d3.showdist();
    cout<<"d4: ";d4.showdist();


    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS