Const Question - Why is this happening?

Please support our C++ advertiser: Intel Parallel Studio Home
Thread Solved

Join Date: Dec 2006
Posts: 1,089
Reputation: vijayan121 is a name known to all vijayan121 is a name known to all vijayan121 is a name known to all vijayan121 is a name known to all vijayan121 is a name known to all vijayan121 is a name known to all 
Solved Threads: 164
vijayan121 vijayan121 is offline Offline
Veteran Poster

Re: Const Question - Why is this happening?

 
1
  #11
Sep 28th, 2008
this is nothing specific to constructors or passing parameters to functions.
it is just the application of the C++ rules for resolving a call to an overloaded function.
  1. #include <iostream>
  2.  
  3. void foobar( int& arg )
  4. { std::cout << "foobar( int& )\n" ; }
  5.  
  6. void foobar( const int& arg )
  7. { std::cout << "foobar( const int& )\n" ; }
  8.  
  9. int main()
  10. {
  11. int i = 7 ;
  12.  
  13. foobar(i) ; // foobar( int& arg ) : exact match
  14. // foobar( const int& ) : conversion from int& to const int&
  15. // exact match preferred over conversion
  16.  
  17. const int j = 7 ;
  18. foobar(j) ; // foobar( const int& arg ) : exact match
  19. // foobar( int& arg ) can't be called at all ( no conversion )
  20.  
  21. }

in your snippet:
  1. int main ()
  2. {
  3. MyClass f(4);
  4. Func (f); // make copy of object f. f is a modifiable lvalue
  5. // overload resolves to exact match : MyClass::MyClass( MyClass& )
  6.  
  7. const MyClass& g = f ;
  8. Func (g); // make copy of object g. g is not a modifiable lvalue
  9. // call MyClass::MyClass( const MyClass& ) to make the copy
  10. }
the copy constructor that takes a non-const object as argument is used to make copies of non-const objects.
and the copy constructor that takes a const object as argument is used to make copies of const objects.
Reply With Quote Quick reply to this message  
Join Date: Jan 2008
Posts: 3,810
Reputation: VernonDozier has a reputation beyond repute VernonDozier has a reputation beyond repute VernonDozier has a reputation beyond repute VernonDozier has a reputation beyond repute VernonDozier has a reputation beyond repute VernonDozier has a reputation beyond repute VernonDozier has a reputation beyond repute VernonDozier has a reputation beyond repute VernonDozier has a reputation beyond repute VernonDozier has a reputation beyond repute VernonDozier has a reputation beyond repute 
Solved Threads: 501
Featured Poster
VernonDozier VernonDozier is offline Offline
Senior Poster

Re: Const Question - Why is this happening?

 
0
  #12
Sep 28th, 2008
Okay, thanks guys! That's very helpful. I'm going to mark this one solved.
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC