4

Let's say in a class a constructor is overloaded. Can multiple data members be initialized for the single object using different constructors of the same class?

eg :

class demo{

    int size;
    double k;
    public:
    demo(int s){
        size=s;
    }
    demo(double p){
      k = size+p;
    }
    void show(){
      cout<<size<<" "<<k<<"\n";
    }
};

int main(){

    demo a = demo(0);
    a = 4.7;
    a.show();
    return 0;
}

Is this possible?

Chris Mukherjee
  • 841
  • 9
  • 25
  • 1
    What are you asking? If you construct with a double, `k` is undefined because `size` is undefined and `k` is an undefined value plus `p`. – Ben Jun 19 '14 at 13:50

3 Answers3

2

You should define a ctor which can take multiple parameters to initialize multiple data members:

demo(int s, double p) {
    size = s;
    k = size + p;
}

and then

int main() {
    demo a(0, 4.7);
    a.show();
    return 0;
}
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
2

I think you're after the Builder Pattern.

Quentin
  • 62,093
  • 7
  • 131
  • 191
2

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):

  1. 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
    
  2. 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
    
  3. 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 ;
}
Community
  • 1
  • 1
jliv902
  • 1,648
  • 1
  • 12
  • 21