No, once the object is constructed, it's constructed.
Let's go through your code and see what it does (assuming no optimizations, please note that many modern compilers will do some copy-elision even in debug or -O0 modes):
demo(0);
The code demo(0)
calls the demo(int s)
constructor. A temporary rvalue is created. So now we have a temporary object with the values:
size = 0
k = uninitialized
demo a = demo(0);
demo a
is then created using an implicit copy constructor.
We now have a demo
object named a
with the following values:
size = 0
k = uninitialized
a = 4.7;
Because a
is already constructed, this will call an implicit assignment-operator. The default assignment-operator will copy all the values from one object into the other object. This means the 4.7
needs to be converted into a demo
object first. This is possible because of your demo(double p)
constructor.
So a temporary demo
object will be created with the values:
size = uninitialized
k = uninitialized + 4.7 = undefined
These values will be copied into a
and so both of a
's data members will be undefined.
Possible Solutions
songyuanyao's solution of using a constructor with multiple parameters is one good way of doing it.
Using setters is another way.
Either way, I would recommend having your constructors provide default values for your data-members.
demo(int s)
{
size = s;
k = 0.0; // or some other suitable value
}
Here's how you could create a setter.
void setK (double p)
{
k = size + p;
}
You could then do this:
int main ()
{
demo a (0) ;
a.setK (4.7) ;
a.show () ;
return 0 ;
}