![]() |
A class with operator overloading
I'm new to c++. I recently read a book on it. After reading the book i just wanted to get some practical experience. Now i'm trying to get "operator overloading" to work. I have a Car class and all i want to do is increment the Honda's speed by 1, (from the Car class). Doing "++Honda" (Honda is the object). However, Instead of increamenting by 1 it increments by approx ONE HUNDRED MILLION. What am i doing wrong??
:
#include <iostream> |
With unary operators, they are evaluated right to left, not left to right, so in your code, the ++ operation is done to itsSpeed before *. This causes the pointer to be incremented, rather than the value stored at the pointer's address, which is what you meant to do.
Simple fix: :
++*itsSpeed; |
Thanks for your help. Unfortunately, this doesn't seem to fix the problem. I tried
:
const Car& Car::operator++()The result, still give me a value in the millions when incremented. Just try running the program and you'll see. |
You also have to change on the Honda object.
|
I see the problem now, I wasn't paying too much attention before. Overloaded operators can only be used on the the object "value". If you declare a pointer to an object, any operators you do on that pointer will be done to the pointer, not to the data. So you must declare the car on the stack or if you have a pointer to a Car (call the pointer variable Honda), you can use ++*Honda.
Method one: :
Car Honda;Method 2: :
Car * Honda2 = new Car;I ran your code on both of these and it worked fine. |
Yeah ur right.. and wow can these pointers can get tedius.
I'm using pointers in this class to get practice with it. However, is there really a point to be using pointers in this program? |
Quote:
It is good to practice them though, because practice makes perfect (it is said) ;). |
| All times are GMT -5. The time now is 4:39 PM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC