OOP .. classes and copy constructors

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>

using namespace 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 = new int;
   *ptr = len;
}

Line::Line(const Line &obj) {
   cout << "Copy constructor allocating ptr." << endl;
   ptr = new int;
   *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
Last edited on
could u show me an example of how is it done ... just a couple of lines code so that i could get a clear image of what u r saying .. Line<obj> thing
1
2
3
4
5
6
7
8
9
10
11
12
13
14
template<typename T>
class Link
{

...

};

class Object
{
...
};

Link<Object> line;//create a Link of Object objects;  
thank you :)
Topic archived. No new replies allowed.