dimanche 19 avril 2015

How Does the copy constructor in c++ work?

How does the copy constructor work when i am not passing "const Class &obj" to the constructor when i passing "obj" into a function. i got this doubt as the book on i c++ is was reading just mentioned what a copy contructor was and how to implement it. but did not mention how it was being called. i am new to c++. i googled it but could not find out how it was being called. Thanking You in advance:)



class Line{

public:
int getLength( void );
Line( int len ); // simple constructor
Line( const Line &obj); // copy constructor

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
}

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;
}

Aucun commentaire:

Enregistrer un commentaire