DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/)
-   C++ (http://www.daniweb.com/forums/forum8.html)
-   -   Getting a constant conversion error (http://www.daniweb.com/forums/thread123445.html)

henpecked1 May 9th, 2008 5:09 pm
Getting a constant conversion error
 
I'm having a little problem with a conversion error during compile. Here is the code:

#include <iostream>
using namespace std;

class costOfItem
{
        public:
        costOfItem(float i_cost);
        void printMe();

          private:
          const float price;

};
// Free functions
void displayPrice(costOfItem z)  { z.printMe(); }
void displayRefPrice(costOfItem &z) { z.printMe(); }
void displayConstRef(const costOfItem &z) { z.printMe(); }
Now in the last line it gives me the error cannot convert 'this' pointer from const costOfItem to costOfItem conversion loses qualifiers. I'm assuming there is a problem with the current instance of the object (which I believe is what 'this' points to, please correct me if I'm wrong about that) and it seems to be trying to convert it to a non const. What seems to be the problem and how do I fix it?

twomers May 9th, 2008 5:38 pm
Re: Getting a constant conversion error
 
Maybe try a:
void printMe const {
 // Code here...
}

henpecked1 May 9th, 2008 5:42 pm
Re: Getting a constant conversion error
 
Do you mean to add the const portion in the member function definition of printMe? And am I right about the 'this' portion of what I posted?

dougy83 May 9th, 2008 10:20 pm
Re: Getting a constant conversion error
 
Both the member function declaration and definition will require the const modifier. This tells the compiler that the function is an 'inspector' function and will not modify anything in the object (which is required when using a const object).

About your 'this' question, 'this' is a pointer to the instance of the object.


All times are GMT -4. The time now is 5:16 am.

Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC