Can't figure out what's wrong with this code

T

Taras_96

Hi everyone,

I can't figure out why g++ complains about this code. I gave it to a
programmer friend and he couldn't work it out either. It's quite
simple code, so it's puzzling me. The error I get is:

==========================================

copy_constructor.cpp: In copy constructor `MyCounter::MyCounter(const
MyCounter&)':
copy_constructor.cpp:23: error: passing `const MyCounter' as `this'
argument of `const int MyCounter::getValue()' discards qualifiers

The code is:
==========================================

#include <iostream>

using namespace std;

class MyCounter
{
public:
MyCounter();
~MyCounter();
MyCounter(const MyCounter &);
const int getValue() {return itsVal;}
private:
int itsVal;
};

MyCounter::MyCounter():
itsVal(0)
{
}

MyCounter::MyCounter(const MyCounter & toCopy)
{
itsVal = toCopy.getValue();
}

MyCounter::~MyCounter()
{
}

===================================

If I write 'toCopy.itsValue' instead, the code compiles

Any help would be appreciated

Thanks

Taras
 
I

Ian Collins

Taras_96 said:
Hi everyone,

I can't figure out why g++ complains about this code. I gave it to a
programmer friend and he couldn't work it out either.

Can't be a C++ programmer then!
#include <iostream>

using namespace std;

class MyCounter
{
public:
MyCounter();
~MyCounter();
MyCounter(const MyCounter &);
const int getValue() {return itsVal;}
private:
int itsVal;
};

MyCounter::MyCounter():
itsVal(0)
{
}

MyCounter::MyCounter(const MyCounter & toCopy)
{
itsVal = toCopy.getValue();

getValue() isn't a const member function, so you can't call it on a
const object.
 
S

suman.nandan

Can't be a C++ programmer then!








getValue() isn't a const member function, so you can't call it on a
const object.

Instead of writing
const int getValue() {return itsVal;}
write
const int getValue() const { return itsVal;}

Thanks,
Suman Nandan
 
T

Taras_96

Thanks Ian and Suman, that was the problem. I'll make sure I give my
friend this link :D
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,015
Latest member
AmbrosePal

Latest Threads

Top