C++ Overload Typecast to Double - c++

I'm working on an another assignment and I can't figure out how to overload a typecast to double. I need to provide the implementation. Would appreciate some help. Thanks!
Here's the function prototype/declaration in my HugeInteger.h file.
operator double(void)const;
Here's a sample of code to test the overloaded type cast to double operator.
cout << "\n****** Test overloaded type cast to double operator ******\n";
cout << "\nA = " << A << "\nB = " << B << "\n";
double dA = (double)A; // one way to invoke cast operator
double dB = static_cast<double>(B); // another way to invoke cast operator
cout << "\nA cast to a double is: " << dA;
cout << "\nB cast to a double is: " << dB << '\n' << endl;

struct Money {
operator double() { return _amount; }
private:
double _amount;
};
int main() {
Money Account;
double CashOnHand = Account;
}
This is a demo in Micrsoft.It's a typecast(auto) from user's type to double. So I think it's a good way to do your work. You are not limited to the function ,you can do more in it ,or build a frame around it. I hope this is helpful.
By the way , ambiguous !!!

Related

Assignment operator overloading: returning void versus returning reference parameter [duplicate]

This question already has answers here:
Why should the assignment operator return a reference to the object?
(4 answers)
Closed 6 years ago.
Some of the assignment overloading operator examples I see online look like this:
#include <iostream>
using namespace std;
class Distance {
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
// required constructors
Distance(){
feet = 0;
inches = 0;
}
Distance(int f, int i){
feet = f;
inches = i;
}
void operator = (const Distance &D ) {
cout << "assigning..." << endl;
feet = D.feet;
inches = D.inches;
}
// method to display distance
void displayDistance() {
cout << "F: " << feet << " I:" << inches << endl;
}
};
int main() {
Distance D1(11, 10), D2(5, 11);
cout << "First Distance : ";
D1.displayDistance();
cout << "Second Distance :";
D2.displayDistance();
// use assignment operator
D1 = D2;
cout << "First Distance :";
D1.displayDistance();
return 0;
}
They return void from the overloaded function. This makes sense to me if D1 is the object being called.
Other examples return a reference to a class object.
#include <iostream>
using namespace std;
class Distance {
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
// required constructors
Distance(){
feet = 0;
inches = 0;
}
Distance(int f, int i){
feet = f;
inches = i;
}
Distance& operator = (const Distance &D ) {
cout << "assigning..." << endl;
feet = D.feet;
inches = D.inches;
return *this;
}
// method to display distance
void displayDistance() {
cout << "F: " << feet << " I:" << inches << endl;
}
};
int main() {
Distance D1(11, 10), D2(5, 11);
cout << "First Distance : ";
D1.displayDistance();
cout << "Second Distance :";
D2.displayDistance();
// use assignment operator
D1 = D2;
cout << "First Distance :";
D1.displayDistance();
return 0;
}
This does not make sense to me (when taking the first example into consideration). If in the first example D1 = D2; invokes something like D1.=(D2);, why would the second example work in that case? Is it something like D1 = D1.=(D2);? And does it make any difference at the end of the day?
Although C++ language lets you overload assignment operator with any return type, including void, you should strongly consider following a widespread convention of returning a reference to the assignee from the operator.
The rationale for it is that
A = B;
will work no matter what the assignment returns, while
A = B = C;
which is a perfect chain of assignments will break, unless B = C returns something assignment-compatible to A (which is usually an object of the same type as A).
Another problem is in situations when you must compare the object as part of a larger expression, for example
mytype obj;
while ((obj = read_obj(cin)) != END_OBJ) {
...
}
Hence, the biggest drawback to returning void is inability to chain assignments and use them in places where void is not allowed.
As a convention, assignment operator usually returns reference (to *this); which makes it possible to chain the assignment, just like the behavior of those built-in types. e.g.
Distance D1, D2, D3;
D1 = D2 = D3;
For D1 = D2;, it's equivalent with D1.operator=(D2);. It doesn't change for the 2nd case, the returned value is just discarded. For D1 = D2 = D3;, it's equivalent with D1.operator=(D2.operator=(D3));. Note the returned value (i.e. reference to D2) is used as the argument for the assignment operator called on D1.

how can a void function be called to the main, if there are no returns?

I wanted to create a function that retrieves all the information from previous functions within the same Class, and prints the values that were returned in the format of a bunch of cout statements, there is nothing for me to return in this PrintStatement() function, so I would create a void function, correct? My issue is in the int main(), I cannot cout a void function.
this is my account header file, and the function piece from my account.cpp file.
class Account {
public:
//Object constructor
Account(char firstName[], char lastName[], char sinNumber[], double balance, int accountType, int transactions);
//Object operations
double DepositAmt(double amount);
double WithdrawAmt(double amount);
void PrintStatement();
double getFinalBalance(double fbal);
string getAccountType();
double getTransactions (double Deposit, double Withdraw);
private:
//Object properties
char firstName[255];
char lastName[255];
char sinNumber[255];
double balance;
int accountType;
int transactions;
};
void Account::PrintStatement()
{
cout << "First Name: " << firstName << endl;
cout << "Last Name: " << lastName << endl;
cout << "SIN Number: " << sinNumber << endl;
cout << "Account Type: " << accountType << endl;
cout << "Final Balance: " << balance << endl;
cout << "Transactions: " << transactions << endl;
};
the global variables have already been initialized.
What I've tried:
I originally tried to cout << account.PrintStatement() << endl; however I get an error C2679 (binary '<<' : no operator found which takes a right-hand operand of type 'void' (or there is no acceptable conversion)
I thought maybe changing things to apply to a string function instead would work, but instead I get a bunch of int conversion errors etc.
I'm unsure of what to do.
I am required to put these in a function just to be clear.
I tried using this question https://stackoverflow.com/questions/12766858/how-to-call-void-function-from-main to help me, it made sense that the poster was using a reference, but I do not have that. Is there another way?
I originally tried to cout << account.PrintStatement() << endl;
Well, the expression account.PrintStatement() is abject nothingness because the function has a void return type. As you've indicated, the function returns nothing, so there is nothing to stream to cout.
The function itself has already streamed a bunch of stuff to cout, fulfilling all your couty needs. So, simply invoke it:
account.PrintStatement();
That's it!
Just call the method on your instance of the class. It doesn't need to return anything; it will do the counts you want and then return to main.
When we use cout<<something_here, the compiler will interpret it as "print the value of something_here". Now, something_here can be a lot of things. When it is a function, cout will print the value returned by the function. In your case, the return type is void i.e. nothing. So, there is nothing to print.
To fix your issue, you can directly call account.PrintStatement(); since you have already printed what you wanted to print inside this function.

Combining overloaded operators with 'new' object

i'd like to ask something rather difficult for me; I have to make a calendar-type program, but with an overloaded '+=' operator.
So it goes like this:
template<typename T1,typename T2,typename T3> //int,int,int
class T_sort_data{
T1 p1;
T2 p2;
T3 p3;
public:
T_sort_data(){
cout << "\n\t Constructed at [" << this << "]\n";};
/ friend ostream& operator<<(ostream& os,const T_sort_data& obj) // get function
{
os << "\nDay : " << obj.p1 << " \n";
os << "Month : " << obj.p2 << " \n";
os << "Year : " << obj.p3 << " \n";
return os;
}*/
void set_date(){
int dd,mm,yy;
cout << "\n\n\tPlease input the day, the month and the year : \n\n";
cin >> dd >> mm >> yy;
p1 = dd;
p2 = mm;
p3 = yy;
}
// validator here, which works ...
T_sort_data<int,int,int>& operator+=(const T_sort_data<int,int,int>& second)
{
p1+=second.p1;
return *this;
}
friend istream& operator>>(istream& is, T_sort_data& obj) // set function
{
is >> obj.p1;
is >> obj.p2;
is >> obj.p3;
return is;
}
~T_sort_data(){
cout << "\n\t Deconstructed [" << this << "]\n";};
};
int main(){
T_sort_data<int,int,int> * a = new T_sort_data<int,int,int> ;
bool more = true;
string answ;
a->set_date();
//cin >> a; (this doesn't work)
//validator goes here
//a += a; (this, again, doesn't work)
delete a;
return 0;
}
Whenever I make an object using "T_sort_data a;" those operations work fine, but whenever I use "T_sort_data * a = new T_sort_data;"
shit hits the fan.
Can anyone help me with this?
You didn't post exactly what is going wrong so I have to infer that from the code.
The issue that you're running into is that overloaded operators work on instances or references to objects, not on pointers to objects. In the cases where your code doesn't work, you're dealing with pointers to objects. So, in order to use your overloaded operators, you need to dereference the pointer (effectively turning it from a pointer pointing to a value into the value itself) before applying the operator, for example:
cin >> *a;
or
*a += *a;
T_sort_data a is a variable of type T_sort_data.
T_sort_data * a is a variable of type pointer to T_sort_data.
Your overloaded operators expect their operands to be of type T_sort_data, not pointer to T_sort_data. Use the unary * operator to dereference the pointers, so that the operand types are what the operators expect.
This is pretty fundamental. Here's the same thing with int and std::cout: http://codepad.org/N07Xckdy

Return value of overloaded <<

#include <iostream>
using namespace std;
struct info {
info(int x, int y) : x(x), y(y) {}
int x;
int y;
};
ostream& operator<<(ostream& out, const info &myinfo){
out << myinfo.x << " " << myinfo.y;
return cout;
}
int main() {
info a(1,2);
info b(3,4);
cout << a << " " << b << endl;
}
The output of the above program seems fine even with the incorrect overload of operator <<.
Can anyone tell me what is the effect of this overloading problem? I know the overloading function should return out instead of cout, but how does the above version behave?
In this case, since you are passing in std::cout to the overloaded operator<<, there is no difference in behavior. Generally, though, you would cause the " " << b << std::endl to get sent to std:cout, while your a would go to whatever you passed in.
For example:
info a(1,2);
info b(3,4);
std::ostringstream ss;
ss << a << " " << b << std::endl;
would cause a to go to ss.
It will work in this situation, obviously, because the target stream is cout. It will break in other situations.
It just happens to work here, because out and cout refers to the same object.

'SalesTaxPct' was not declared in this scope

I am new to C++. I am struggling with the pass by value thing, and no one can explain what I am doing wrong to me in a way I can understand. I know this is my fault, but Ii am asking for help with my code. HELP PLEASE!
#include <iostream>
using namespace std;
double getValues();
double getSalesTax(double SalesTaxPct);
double gettotal_price(double base, double opt);
void PrintFinal(double base,double opt,double SalesTaxPct);
// function to control all other functions
int main()
{
getValues();
getSalesTax(SalesTaxPct);
PrintFinal(base,pt,SalesTaxPct);
}
// function to calculate sales tax percent into decimal
double getSalesTax( double SalesTaxPct )
{
double SalesTax;
SalesTax = SalesTaxPct / 100;
return SalesTax;
}
// function to find total
double gettotal_price(double base, double opt, double SalesTax)
{
return = (base + opt) * (1 + SalesTax);
}
// function to show user all values input and also total
void PrintFinal(double base, double opt, double SalesTaxPct)
{
cout << "Base vehicle price: $" << base << endl;
cout << "Options Price: $" << opt << endl;
cout << "Sales tax pct: " << SalesTaxPct << "%" << endl;
cout << "Total vehicle price: $" << gettotal_price(double base, double opt, double SalesTax) << endl;
}
// function to get input values
void getValues()
{
double base, double opt, double SalesTaxPct;
cout << "Enter a base vehicle price: " << endl;
cin >> base;
cout << "Enter options price: " << endl;
cin >> opt;
cout << "Enter a sales tax percent: " << endl;
cin >> SalesTaxPct;
}
When you are in main, let's go over what the program sees:
int main()
{
getValues();
getSalesTax(SalesTaxPct);
PrintFinal(base,pt,SalesTaxPct);
}
The only variables that your program knows about at this point are: getValues(), getSalesTax(), gettotal_price(), and PrintFinal(). The warning is telling you that at this point of your program, SalesTaxPct was not declared yet, and looking at our list of variables / functions that the program knows about, we see that, indeed, SalesTaxPct is not on the list. Where do we expect the value of SalesTaxPct to come from?
It looks like that comes from the function getValues, and we are getting it from user input. However, any time that you have { ... }, the stuff inside the braces cannot be accessed outside. Therefore, SalesTaxPct is only "in scope" inside the function getValues. If you want it to be accessible outside of that function (which you do), you need to change things around a bit.
int main()
{
double base;
double opt;
double SalesTaxPct;
getValues(base, opt, SalesTaxPct);
getSalesTax(SalesTaxPct);
PrintFinal(base, opt, SalesTaxPct);
}
Now all of our variables still exist when we need them in main. However, there is still a problem here. We want the changes we pass into getValues to change the variables in main. This means we cannot pass "by value" because that will first make a copy, and then change those copies (not what we want). Instead, we need to say that the changes we make need to be returned from the function some how:
void getValues(double & base, double & opt, double & SalesTaxPct);
That little & there means that rather than making a copy and changing that copy, we are telling the function to operate on the variable we pass in directly. This is referred to as "pass by reference".
There are some similar problems in other parts of your code, but perhaps now you can figure out how to fix them.