Zhijie Xia
Zhijie Xia

Reputation: 27

Call another object's method in constructor C++

I am trying to call otherObjectArea's getter from the copy constructor and I countered compile error. I am doing it like Java. How should I do it correctly in C++?

class ObjectArea
{
private:
int x, y, width, height;

public:
ObjectArea(int x, int y, int width, int height)
{
    this->x = x;
    this->y = y;
    this->width=width;
    this->height = height;
}

ObjectArea():ObjectArea(0,0,0,0){}


ObjectArea(const ObjectArea &otherObjectArea){
    this->x = otherObjectArea.getX();
    this->y = otherObjectArea.getY();
    this->width = otherObjectArea.getWidth();
    this->height = otherObjectArea.getHeight();
}

int getX(){
    return this->x;
}

int getY(){
    return this->y;
}

int getWidth(){
    return this->width;
}

int getHeight(){
    return this->height;
}
};

The compile error:

ObjectArea.cpp:19:40: error: passing ‘const ObjectArea’ as ‘this’ argument discards qualifiers [-fpermissive]
   19 |         this->x = otherObjectArea.getX();
      |
                                        ^
ObjectArea.cpp:25:9: note:   in call to ‘int ObjectArea::getX()’
   25 |     int getX(){
      |         ^~~~

Many thanks.

Upvotes: 1

Views: 70

Answers (2)

User
User

Reputation: 610

You are making a call to non const function from a const object


class ObjectArea
{
private:
int x, y, width, height;

public:
ObjectArea(int x, int y, int width, int height)
{
    this->x = x;
    this->y = y;
    this->width=width;
    this->height = height;
}

ObjectArea():ObjectArea(0,0,0,0){}


ObjectArea(const ObjectArea &otherObjectArea){
    this->x = otherObjectArea.getX();
    this->y = otherObjectArea.getY();
    this->width = otherObjectArea.getWidth();
    this->height = otherObjectArea.getHeight();
}

int getX() const{
    return this->x;
}

int getY() const{
    return this->y;
}

int getWidth() const{
    return this->width;
}

int getHeight() const{
    return this->height;
}
};

Upvotes: 0

mrks
mrks

Reputation: 8333

You are calling getX on a const ObjectArea& reference, i.e., a reference to an object that must not be modified. However, getX is not marked as const, i.e., you do not promise that the method will not modify the object that it is called on.

By changing it to:

int getX() const {
    return this->x;
}

you will be able to call getX on const references. Same for all other methods.

Upvotes: 4

Related Questions