copy constructor
I get a wrong value in the object (a) when i write the copy constructor
why is this? am i doing something wrong?
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
|
#include <iostream>
class counter
{
public:
counter();
counter(int val) { itsVal = val; }
counter(counter &) { } // this is not right
~counter() {}
// FUNCTIONS
int GetVal() const { return itsVal; }
void SetVal(int NewVal) { itsVal = NewVal;}
void Increase() { itsVal += 1; }
counter& operator ++();
private:
int itsVal;
};
counter::counter():itsVal(0) { }
counter& counter::operator ++()
{
itsVal += 1;
return *this;
}
int main()
{
using namespace std;
counter i;
cout << "I : " << i.GetVal() << "\n";
++i;
++i;
counter a = ++i;
++i;
cout << "A : " << a.GetVal() << "\n";
cout << "I : " << i.GetVal() << "\n\n";
return 0;
}
|
Last edited on
By wrong value, I take it you mean and undefined/unpredictable value.
That because your copy constructor does not initialise itsVal
. It should copy the value as you do in the int
constructor.
If i didn't make the copy constructor the compiler makes it
The whole program look will look like
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
|
#include <iostream>
class counter
{
public:
counter();
counter(int val) { itsVal = val; }
counter(counter & rhs) { itsVal = rhs.GetVal(); }
~counter() {}
// FUNCTIONS
int GetVal() const { return itsVal; }
void SetVal(int NewVal) { itsVal = NewVal;}
void Increase() { itsVal += 1; }
counter operator ++();
private:
int itsVal;
};
counter::counter():itsVal(0) { }
counter counter::operator ++()
{
itsVal += 1;
return *this;
}
int main()
{
using namespace std;
counter i;
cout << "I : " << i.GetVal() << "\n";
++i;
++i;
counter a = ++i;
++i;
cout << "A : " << a.GetVal() << "\n";
cout << "I : " << i.GetVal() << "\n\n";
return 0;
}
|
Correct!
the copy ctor should take a
const
reference, not a non-const one.
ie:
|
counter(const counter& rhs) { itsVal = rhs.GetVal(); } // notice the const
|
Topic archived. No new replies allowed.