How do I lazy init class members without a default constructor?
Here is the minimum reproducible example:
#include <stdio.h>
#include <string>
#include <iostream>
using namespace std;
class B{
public:
string name;
B(string n):name(n){
cout <<"B construct by name" <<endl;
};
B(){
cout <<"B construct by deafult" <<endl;
}
};
class A{
public:
B b;
A(){
this->b = B{"name"};
/*
I want to set this->b here,
not set by init list,
without B deafult construct(happen when A delcare).
*/
};
};
int main()
{
A a;
return 0;
}
If you run the minimum reproducible example, it would print:
B construct by default
B construct by name
Can avoid the first log?
Should I use std::optional
, or is my design, as it is, is fundamentally wrong?
I want to set this->b here, not set by init list...
One other option with modern C++ is to use in-class initializer as shown below.
class B{
public:
string name;
B(string n):name(n){
cout <<"B construct by name" <<endl;
};
B(){
cout <<"B construct by deafult" <<endl;
}
};
class A{
public:
B b{"name"}; //use in-class initializer
A(){
};
};
Now the output is as you want:
B construct by name