Answer to Question #181127 in C++ for ayush singh

Question #181127

Create a class Number with a pointer as a data data member of integer type. Write user defined copy constructor to the class and implement the deep copy for the Number class objects. So when a new object is created from an old object of the Number class, pointer data member can point different memory block.


1
Expert's answer
2021-04-13T16:23:45-0400
#include <iostream>

class Number {
public:
    Number(int n) 
        : m_data { new int(n) }
    {}
    ~Number() {
        delete m_data;
    }
    Number(const Number& n)
        : m_data { new int(*n.m_data) }
    {}

    int Value() const noexcept {
        return *m_data;
    }

private:
    int * m_data { nullptr };
};

int main() {
    Number n1(2), n2(3);
    Number n3(n1);
    std::cout << n1.Value() << " ";
    std::cout << n2.Value() << " ";
    std::cout << n3.Value() << " ";
    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