a regular coder
a regular coder

Reputation: 95

Accessing pointers inside class

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.

Upvotes: 2

Views: 600

Answers (2)

Refugnic Eternium
Refugnic Eternium

Reputation: 4291

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)

Upvotes: 6

Serge Ballesta
Serge Ballesta

Reputation: 148880

This is a syntax error. ->* or .* if for pointer to members which are quite different animals (more on cppreferences)

Here you just have a member which happens to be a pointer. You can simply dereference it with *tires or *this->tires.

Upvotes: 3

Related Questions