Create objects in conditional c++ statements

I don't know if I understood your question correctly but can't you just declare report before the if/else block and then initialize inside it?

Report header;

if (...) {
  header = Report();
else
  header = Report(name,company);

Or in a shorter way:

Report header; // calls default constructor

if (shouldInitializeWithParams) {
  header = Report(name,company);
}

Of course this requires you to have the empty constructor defined.


First off, you cannot create an object within a conditional statement and use it after the conditional statement: the two branches of the conditional statement create a scope each and any object created within in destroyed a the end of the branch. That is, you need to come up with a different approach. The simplest approach is probably to delegate the creation of the object to a function which returns the objects as appropriate:

Report makeReport() {
    if (enter_company_name()) {
        ...
        return Report(name, company);
    }
    return Report();
}

...
Report report = makeReport();

An alternative approach is to use the ternary operator to conditonally create the Report one way or another:

bool get_company_name = enter_company_name();
std::string name(get_company_name? read_name(): "");
std::string company(get_company_name? read_company(): "");
Report report = get_company_name? Report(name, company): Report();

All of these approaches assume that the Report class is actually copyable.


We don't know whether class Report is copy-able, so better to use pointers.

Report * header;

if (...) {
  header = new Report();
else
  header = new Report(name,company);

// after all don't forget
delete header;

and of course you should use header pointer like that

header->print_formatted();