On May 26, 11:01 pm, "michael" <s...@begone.netwrote:
Hi All,
why does this
#include <iostream>
using namespace std;
class A {
public:
A (int = 0);
void assign (const A&);
private:
int number;
};
inline A::A(int n): number(n){
cout << "constructor\n";
}
inline void A::assign(const A& a){
number = a.number;
}
int main(){
A a(1);
a.assign(2);
return 0;
}
end up making two constructor calls? I thought the pass by reference would
have avoided the second call....is it beacuse the assign() call has a const
so a second copy must be made?
Thanks for your help
Regards
Michael
The second call is invoked on a temporary. Which would fail if A's
ctor was 'explicit'.
Instead of void A::assign(const A& a) you might consider a rudimentary
setter since class A will already have a compiler generated copy ctor
(assuming the compiler detects that one is needed). Which explains the
output below.
#include <iostream>
class A {
int number;
public:
A(int n = 0) : number(n) { }
void set(const int n) { number = n; }
int get() const { return number; }
};
int main()
{
A a;
a.set(99);
A another(a); // invokes copy
std::cout << another.get() << std::endl; // 99
}
___
That copy ctor looks something like this (look familiar?)
A::A(const A& copy)
{
number = copy.number;
}