简体   繁体   中英

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.

You are calling getX on a const ObjectArea& reference, ie, a reference to an object that must not be modified. However, getX is not marked as const , ie, 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.

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;
}
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM