Reputation: 67
One of my assignments involve creating a class using a constructor with parameters, where the arguments sent to create the object are based on user input.
#include <iostream>
#include "HRCalc_lib.h"
HeartRates::HeartRates(const std::string &first, const std::string &last,
int day, int month, int year){
firstName = first;
lastName = last;
setBirthYear(year);
setBirthMonth(month);
setBirthDay(day);
}
Note: This is from a .cpp
file where member functions are fully written. All other class syntax is in a header file.
I approached creating an object with this constructor using std::cin
with variables through main
.
#include <iostream>
#include "HRCalc_lib.h"
int main(){
std::string first, last;
int Bday, Bmonth, Byear;
std::cout << "enter your name (first last) & date of birth (dd mm yyyy) seperated by spaces" << std::endl;
std::cin >> first >> last >> Bday >> Bmonth >> Byear;
HeartRates person1(first, last, Bday, Bmonth, Byear);
//further code would be implemented here
return 0;
}
Is there a more direct way of creating the same object without the need for variables in main?
Upvotes: 1
Views: 615
Reputation: 1
Is there a more direct way of creating the same object without the need for variables to store user inputs in main?
Yes, there is. You can use operator overloading. In particular, you can overload operator>>
as shown below:
#include <iostream>
#include<string>
class HeartRates
{
private:
std::string first, last;
int day = 0, month = 0, year = 0;
//friend declaration for overloaded operator>>
friend std::istream& operator>>(std::istream& is, HeartRates& obj);
};
//implement overloaded operator<<
std::istream& operator>>(std::istream& is, HeartRates& obj)
{
is >> obj.first >> obj.last >> obj.day >> obj.month >> obj.year;
if(is)//check that input succeded
{
//do something here
}
else //input failed: give the object a default state
{
obj = HeartRates();
}
return is;
}
int main(){
HeartRates person1;
//NO NEED TO CREATE SEPARATE VARIABLES HERE AS YOU WANT
std::cout << "enter your name (first last) & date of birth (dd mm yyyy) seperated by spaces" << std::endl;
std::cin >> person1; //this uses overloaded operator>>
return 0;
}
The output of the above program can be seen here.
Here when we wrote:
std::cin >> person1;
we're using the overloaded operator>>
and so you don't need to create separate variables inside main
.
Upvotes: 2