Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing pointers inside class

Tags:

c++

i am trying to use a pointer variable in a class but instead it gave me an error

Car.cpp:15:16: error: right hand operand to ->* has non-pointer-to-member type 'int *' return this->*tires;

here is my program

main.cpp

#include <iostream>
#include "Car.h"

using namespace std;

int main(){
    int x = 5;
    Car honda("honda", &x);
    
    cout << honda.getBrand() << " " << honda.getTires() << endl;
    x = 6;
    cout << honda.getBrand() << " " << honda.getTires() << endl;

    return 0;
}

Car.h

#ifndef CAR_H
#define CAR_H

#include <string>

using namespace std;

class Car {
    private:
        string brand;
        int *tires;
    public:
        Car(string brand, int *tires);
        string getBrand();
        int getTires();
};

#endif

Car.cpp

#include "Car.h"

using namespace std;

Car::Car(string brand, int *tires){
    this->brand = brand;
    this->tires = tires;
}

string Car::getBrand(){
    return this->brand;
}

int Car::getTires(){
    return this->*tires;
}

on Car.cpp the method Car::getTires lies the error which seems to already be logical, i tried to use this->tires or this->(*tires) but it still gave me error.

like image 362
a regular coder Avatar asked Jun 10 '26 21:06

a regular coder


1 Answers

The entire variable is called this->tires, the this referring to the current object and the tires referring to the member itself.

As such, you need to dereference the variable and not 'a part of it`.

Either use:

int Car::getTires(){
    return *tires;
}

which works, because the this is implied automatically by the compiler or

int Car::getTires(){
    return *(this->tires);
}

return *this->tires; should also work, because the operator precedence puts the -> before the * (meaning it first evaluates the this prior to trying dereferencing the variable). (https://en.cppreference.com/w/cpp/language/operator_precedence)

like image 190
Refugnic Eternium Avatar answered Jun 12 '26 11:06

Refugnic Eternium



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!