I am learning C ++ and I just got to the object-oriented chapter. I have a question about creating objects inside if statements.
The problem I'm working on is talking about creating a class that displays the title of the report. The class has a default constructor, which sets the company name and report name for the common thing, and also, if the user wants, has a constructor that takes two arguments (company names and report name).
The problem is: "The two-component default constructor must specify these [company and report names] when creating a new Report object. If the user creates the Report object without any arguments, use the default values. Otherwise, use the user-specified values for the names. "
So my question is: how to create these objects? I understand how to create an object without any arguments (i.e., Report newobj;), as well as with arguments (i.e. Report newobj (string string);). Basically, I get how to create these objects initially at the top of my main function. But is it possible to create them inside if the statements are based on the user's choice? Here is what I still have and obviously this is not working:
#include <iostream> #include <string> #include "report.h" using namespace std; bool enter_company_name(); // return true if user wants to enter company name bool print_form(); // return true if user wants to print in formatted output int main() { string company_name, report_name; bool name = false, format = false; name = enter_company_name(); format = print_form(); if (name) { cout << "Enter company name: "; getline(cin, company_name); cout << "Enter report name: "; getline(cin, report_name); Report header(company_name, report_name); // THIS IS MY PROBLEM } else Report header; // THIS IS MY PROBLEM if (format) header.print_formatted(); else header.print_one_line(); return 0; } bool enter_company_name() { char choice; cout << "Do you want to enter a name?\n>"; cin >> choice; if (choice == 'y' || choice == 'Y') return true; else return false; } bool print_form() { char choice; cout << "Do you want to print a formatted header?\n>"; cin >> choice; if (choice == 'y' || choice == 'Y') return true; else return false; }
So, I want to create an object using the default values if none are specified, or create it with custom values if this choice is specified. I just can't figure out how to do this interactively in C ++. So far I have not been able to find a single similar question.
The closest thing I came across uses pointers to do something similar to what I want to do, but the book I use has not yet received the pointers, and I want to try to figure out a way to do this what remains in within the section in which I work (i.e. without using pointers).
I did not include the header file or the class implementation file because I do not think they are relevant here.
Thank you in advance!
c ++ object constructor class if-statement
nik
source share