2
#include <iostream>

using namespace std;

class object{
    object* Next;
};

int main()
{
    char* c = new char[64];
    reinterpret_cast<object*>(c);
    c->Next;

    return 0;
}

Why do I get the error

main.cpp:21:8: error: request for member ‘Next’ in ‘* c’, which is of non-class type ‘char’

when I try to access the Next pointer even though I have casted the allocated memory into object type? How can I access the Next pointer?

I only used char type because I wanted to allocate exactly 64 bytes of memory.

user3702643
  • 1,465
  • 5
  • 21
  • 48
  • `c` is a `char *` and has no member `Next`. – Sid S Jan 24 '19 at 05:00
  • 1
    No offence, but if this is the issue you are faced with, you need [a good book about C++](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) instead of messing about with the dangers of `reinterpret_cast`. – StoryTeller - Unslander Monica Jan 24 '19 at 05:59

2 Answers2

6

reinterpret_cast returns a pointer with the reinterpreted type.

E.g.

char* c = new char[64];
object* o = reinterpret_cast<object*>(c);
o->Next;

You cannot change the type of c once it has been declared. In the above example c and o point to the same place, but o is a object* so o->Next is valid.

You also need to make Next public before it can be accessed from outside of a member function.

class object{
public:
    object* Next;
};

It's worth noting that the example above results in undefined behavior as you did not actually put any data into the memory pointed to by c. o->Next will be a garbage value.

Increasingly Idiotic
  • 5,700
  • 5
  • 35
  • 73
  • 2
    It's worse than it being a garbage value; UB means that the compiler can do whatever it wants. A garbage value is the most likely, but it could also be a segfault or something. – Daniel H Jan 24 '19 at 05:18
4

According to Wikipedia:

(by default access to members of a class is private). The private members are not accessible outside the class; they can be accessed only through methods of the class. The public members form an interface to the class and are accessible outside the class.

And tutorialspoint:

By default all the members of a class would be private, for example in the following class width is a private member, which means until you label a member, it will be assumed a private member

Meaning that if you want to access a data member outside the class, you need to set its access modifier to public.

class object{
public:
    object* Next;
};

Or, alternatively, you could make a getter

class object{
    object* Next;
public:
    object* getNext() {
        return Next;
    }
};

And then, to access it:

c->getNext();

Edit: I just realized that the error you got was not for calling a private member. So you can probably disregard this for that error. That said, you still might want to be watch out for this, unless you didn't post the full code and know that already.