You can not initialize one class data member in another class if base class does not have default constructor
class base{
int _x;
public:
base(){}
base(int x): _x{x} {}
};
class derive{
base b; //we are here calling default constructor of base as no //parameter passed
public:
derived(base x) {b = x;} //called first, copy constructor called from here
};
You can not initialize base class data member from child class without initializer list
class base{
int _x;
public:
base(int x): _x{x} {}
}
class derived : public base{
int _y;
public:
derived(int x,int y): base{x}, _y{y} {}
//base{x} calls constructor of base class
/* this is not gonna work, _x is private here
so you must use intializer list
derived(int x, int y){
_x = x;
_y = y;
}
*/
};
int main(){
derived d(4,5);
return 0;
}
You have temp variable same as data member
You can not initialize data member with same name as temporary variable without initializer list
class base{
int _x;
public:
base(int _x): _x{_x} {}
//base(int _x) { _x = _x; } there is errorneous
};
Using initializer list optimize you code a little more
Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!
Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.
Top comments (0)