Initialize multiple variables with constructor overload

Let's say the constructor is overloaded in the class. Is it possible to initialize several data elements for one 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 it possible?

+4
source share
3 answers

No, after creating the object, it is being built.

Skip your code and see what it does (in the absence of optimizations, note that many modern compilers will do copy-elision even in debugging or -O0 modes):

  • demo(0);

    demo(0) demo(int s). rvalue. , :

    size = 0
    k = uninitialized
    
  • demo a = demo(0);

    demo a .

    demo a :

    size = 0
    k = uninitialized
    
  • a = 4.7;

    a , . . , 4.7 demo. - demo(double p).

    , demo :

    size = uninitialized
    k = uninitialized + 4.7 = undefined
    

    a, a undefined.

songyuanyao - .

seters - .

, , .

demo(int s)
{
    size = s;
    k = 0.0; // or some other suitable value
}

.

void setK (double p)
{
    k = size + p;
}

:

int main ()
{
    demo a (0) ;

    a.setK (4.7) ;
    a.show () ;

    return 0 ;
}
+2

ctor, :

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

int main() {
    demo a(0, 4.7);
    a.show();
    return 0;
}
+2
+2

Source: https://habr.com/ru/post/1545246/


All Articles