Search code examples
c++constructorparameterized

Dynamic parametrized constructor issue in C++


I am here including a simple program that written in C++ where I am trying to use a parametrized constructor. My idea is to instantiate the class dynamically and capture the required task. But whenever I run the program and enter the task 1 it simply prints the two lines (i.e. Enter Name.Enter Tel.No.). It is actually supposed to print "Enter Name." then input the name, And then again print "Enter Tel.No.". How can I fix the issue? I have to use parametrized constructor dynamically while creating an object.

    #include <iostream>
    #include <conio.h>
    #include <fstream>
    #include <string>

using namespace std;

class myClass
{
     string  fullname,telephone;

public:
       myClass(int taskType = 2)
       {
          if(taskType==1)
          {
              add_record();                  
          }
          else if(taskType==2)
          {
              //view_records();
          }
          else if(taskType==3)
          {
              //delete_record();
          }else{
             // custom_error();
          }        
       }  
void add_record()
{
cout << "Enter Name.\n";
getline(cin, fullname);
cout << "Enter Tel. No.\n";
getline(cin, telephone);
}
   };

    main (){
          int myTask;
      cout << "Enter a Task-Type. \n"
           << "1 = Add Record,"
           << "2 = View Records,"
           << "3 = Delete a Record\n\n";
      cin >> myTask;
      myClass myObject(myTask);
           getch();
     }

Solution

  • This probably has nothing to do with your constructor, but rather with the mixing of cin >> and getline. Add a getline to a garbage variable after cin >> myTask and it should work.