Reputation: 93
This program gives the correct output, but I can't understand how. How is the default constructor called at the time of the declaration of the object?
#include <iostream>
using namespace std;
class GuessMe {
private:
int *p;
public:
GuessMe(int x=0)
{
p = new int;
}
int GetX()
{
return *p;
}
void SetX(int x)
{
*p = x;
}
~GuessMe()
{
delete p;
}
};
int main() {
GuessMe g1;
g1.SetX(10);
GuessMe g2(g1);
cout << g2.GetX() << endl;
return 0;
}
Upvotes: 0
Views: 82
Reputation: 227390
This constructor has a default parameter:
GuessMe(int x=0)
That means that when a GuessMe
is default constructed, it is as if it had been called with an argument with value 0
. Note that the constructor parameter isn't used for anything in your code. Also note that p
is set to point to an uninitialized integer here:
p = new int;
so calling GetX()
before calling SetX()
would yield undefined behaviour. Presumable you want to use the value of x
to set p
:
GuessMe(int x=0)
{
p = new int(x);
}
or, using initialization instead of assignment,
GuessMe(int x=0) : p(new int(x))
{
}
Also, read up on the rule of three to avoid double-deletes. And then learn to code without raw pointers to dynamically allocated objects.
Upvotes: 5