When a class object is passed by value to any function, the copy constructor is called to create a local object and the destructor is called when the object is returned. But, will copy constructor be called if the object reference is passed?
Asked
Active
Viewed 2,240 times
-3
-
1Did you try it? What happened? – DimChtz Jul 28 '17 at 11:26
-
4Please create a [mcve] and explain what behavior you saw and what you expected – UnholySheep Jul 28 '17 at 11:28
-
1Passing by reference causes no copying, therefore the copy-constructor should not be called. – Some programmer dude Jul 28 '17 at 11:28
-
3Sounds like you could use a [good C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – NathanOliver Jul 28 '17 at 11:29
-
4No, it will not. – Chris Drew Jul 28 '17 at 11:30
-
C++ doesn't have "class objects". – Toby Speight Jul 28 '17 at 12:16
1 Answers
2
Nope, it won't be called.
A reference is an alias, that is, another name for an already existing variable and not for a copy.
Take a look at this example:
class Line {
public:
int getLength( void ){}
// simple constructor
Line( ){
cout<<"constructor"<<endl;
}
// copy constructor
Line( const Line &obj){
cout<<"copy cts\n";
}
};
void callR(Line& l){
cout<<"call by ref\n";
}
void callC(Line l){
cout<<"call by copy\n";
}
int main() {
Line line;
cout<<"before call by reference\n";
callR(line);
cout<<"before call by copy\n";
callC(line);
}
which produces the following output:
constructor -> Line line;
before call by reference
call by ref
before call by copy
copy cts
call by copy
As you can see copy constructor is not called when an object is passed by reference. Think of a reference as a pointer.

Davide Spataro
- 7,319
- 1
- 24
- 36