#include <iostream>
usingnamespace std;
class Line {
public:
int getLength( void );
Line( int len ); // simple constructor
Line( const Line &obj); // copy constructor
~Line(); // destructor
private:
int *ptr;
};
// Member functions definitions including constructor
Line::Line(int len) {
cout << "Normal constructor allocating ptr" << endl;
// allocate memory for the pointer;
ptr = newint;
*ptr = len;
}
Line::Line(const Line &obj) {
cout << "Copy constructor allocating ptr." << endl;
ptr = newint;
*ptr = *obj.ptr; // copy the value
}
Line::~Line(void) {
cout << "Freeing memory!" << endl;
delete ptr;
}
int Line::getLength( void ) {
return *ptr;
}
void display(Line obj) {
cout << "Length of line : " << obj.getLength() <<endl;
}
// Main function for the program
int main( ) {
Line line(10);
display(line);
return 0;
}
this is a code from a tutorial page called tutorialspoint
could u pls answer me the following questions ?
1- how many objects has been created and in which lines ?
2- why when i write <Line Obj;> doesnt work??? isnt it the right syntax for declaring an object from a class ?
Since the constructors and destructors are 'vocal' you'll find, if you ran the program, that two objects are created and destroyed. One is from line 46 where the Line object line is initialized, and the other is from Display(line) since the object is passed to the function as value, not reference and hence generates another copy. If you pass objects to Display() as reference then #objects created would be one.
Line<Obj> would work if Line were a template class instantiated with typename Obj