Answer to Question #185440 in C++ for Alex

Question #185440
Your task is to create a class name polygon that contains 2 data members i.e. length of type float and width (a pointer of type float). Create a single object named “one” in the main and assign values to the data member of the polygon object. Then create another object named “two” that is a copy of the “one”. Create a shallow copy constructor that copies only the pointer data member of the class polygon and then demonstrate that both objects share a common memory i.e. modifying one object in fact modifies the other. Create a display function that will show the values of the polygon object.
1
Expert's answer
2021-04-26T00:28:53-0400
#include <iostream>
using namespace std;
class Polygon{
    float length, *width;
    public:
    Polygon(){}
    Polygon(float l, float w){
        length = l;
        width = new float(w);
    }
    Polygon(const Polygon &N){
        width = N.width;
        length = N.length;
    }
    void modify(float f){
        *width = f;
    }
    void display(){
        cout<<"length: "<<length<<endl;
        cout<<"width: "<<*width<<endl;
    }
};
int main(){
    Polygon one(5, 4), two = one;
    cout<<"One\n";
    one.display();
    cout<<"\nTwo\n";
    two.display();
    cout<<"\nModifying two\n";
    two.modify(6);
    cout<<"\nOne\n";
    one.display();
    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