Copy Constructors and calling functions

Posted by helixed on Stack Overflow See other posts from Stack Overflow or by helixed
Published on 2010-04-17T23:00:49Z Indexed on 2010/04/17 23:03 UTC
Read the original article Hit count: 529

Filed under:
|
|
|

Hello,

I'm trying to call an accessor function in a copy constructor but it's not working. Here's an example of my problem:

A.h

class A {

public:
    //Constructor
    A(int d);
    //Copy Constructor
    A(const A &rhs);

    //accessor for data
    int getData();

    //mutator for data
    void setData(int d);

private:
    int data;
};

A.cpp

#include "A.h"

//Constructor
A::A(int d) {
    this->setData(d);
}

//Copy Constructor
A::A(const A &rhs) {
    this->setData(rhs.getData()); 
}

//accessor for data
int A::getData() {
    return data;
}

//mutator for data
void A::setData(int d) {
    data = d;
}

When I try to compile this, I get the following error:

error: passing 'const A' as 'this' argument of 'int A::getData()' discards qualifiers

If I change rhs.getData() to rhs.data, then the constructor works fine. Am I not allowed to call functions in a copy constructor? Could somebody please tell me what I'm doing wrong?

Thanks,

helixed

© Stack Overflow or respective owner

Related posts about c++

Related posts about copy