0

How can I use constructor and copy constructor and destructor for this program?

Class line { Public: Int getlength (void); Line(int len); Line(const line &obj); ~line(); Private: Int *ptr; }; Line::line(int len) { Cout<<"normal constructor allocating ptr"<<endl; .........................? } Line::line(const line &obj) { Cout<< "copy constructor allocating ptr"<<endl; ........................? } Line::~line(void) { Cout<<"freeing memory"<<endl; ........................? } ........? Are the parts that I don't know what should I put there

26th Jan 2022, 8:08 AM
Nadia
Nadia - avatar
1 Answer
+ 1
//you have it already but just trying to complete code //read the comments to understand and about changes #include<iostream> using namespace std; class line { public: int getlength (void); line(); line(int len); line(const line &obj); ~line(); private: int *ptr; }; //default constructor line::line() { ptr=new int; //setting 0 cout<<"normal constructor allocating ptr"<<endl; } line::line(int len) { ptr=new int(len); //setting value len cout<<"normal constructor allocating ptr"<<endl; } //length function int line::getlength(void) { return *ptr; } //copy constructor line::line(const line &obj) { cout<< "copy constructor allocating ptr"<<endl; } line::~line(void) //distructor { cout<<"freeing memory"<<endl; } //main method int main() { line l1; //calling default constructor line l2(55); //parameter constructor cout<< l1.getlength() << endl; //output 0 cout<< l2.getlength() << endl; //output 55 //destructor called automatically now for both l1, l2 objects. }
26th Jan 2022, 10:09 AM
Jayakrishna 🇼🇳