Bex
Bex

Reputation: 51

Simple pointer object error C++

I made a small program in c++ to learn more about pointer objects. However I keep getting an error that the pointer object "bar" is not a part of the class more specifically:

[Error] 'class ux' has no member named 'bar'

As shown below:

class ux {
private:
    int width;
    int height;

public:
    ux(int, int);
    ~ux();
    int area();
};

ux::ux(int a, int b)
{
    width = a;
    height = b;
}
ux::~ux(){}

int ux::area()
{
    return (width * height);
}

int main(int argc, char** argv) {
    ux * foo;
    ux * bar;

    foo = new ux(2, 2);
    foo->bar = NULL;
    cout << foo->area() << "\n";
    cout << foo->bar << "\n";   
}

Why is this happening? I know it's possible to point to another pointer object with the arrow operator but it is not working here.

---------------------Update-----------------------

I am not trying to do anything with foo->bar I just want to see the address or value printed out but I know that a pointer obj can point to another pointer obj. If someone can please specify a link that shows this technique in use I would greatly appreciate that.

Upvotes: 1

Views: 256

Answers (3)

Mark Ransom
Mark Ransom

Reputation: 308520

The -> isn't used to access arbitrary pointers, it's used to access members of the class. The members of your ux class are width, height, and area. bar is a completely separate variable of type ux, and you would use it e.g. bar->width, bar->height, or bar->area().

Upvotes: 1

galdin
galdin

Reputation: 14074

I know it's possible to point to another pointer object with the arrow operator but it is not working here.

Yes it is possible. The right way to do it is:

foo = bar;

Since foo is a pointer, it is essentially a variable with an address as its value. To make another variable point to the same object, all you have to do is assign the address to the other variable.

As a side note, remember that every new should have a delete.

Upvotes: 0

Nikola Butigan
Nikola Butigan

Reputation: 35

In line foo->bar you are giving an order to object foo to do function from class ux called bar . Your defined class ux does not have attribute/function defined in class. You should read this article about operators .Its maybe easier to learn more about C++ Classes and objects then dive into pointers.

Upvotes: 0

Related Questions