i wrote this code:
class A {
public:
A(){d=2.2;cout<<d;}
A(double d):d(d){cout<<d;}
double getD(){return d;}
private:
double d;
};
class Bing {
public:
Bing(){a=A(5.3);}
void f(){cout<<a.getD();}
private:
A a;
};
int main() {
Bing b;
b.f();
}
i get the output: 2.2 5.3 5.3 instead of 5.3 5.3. it’s something in the constructor…. why am i getting this? how can i fix it?
Your class
Ahas two constructors: a default constructor, which setsdto 2.2, and a constructor taking a double, which setsdto whatever you pass into the constructor.You have a member variable of type
Ain your classBing. This member variable is initialized before the body of theBingconstructor is entered. Since you don’t list theBingmember in the constructor’s initializer list, its default constructor is called. You can explicitly initialize it with the desired value by initializing it in the initializer list: