1

I'm having a problem to understand this line of code:

MyTable *t = (MyTable*)table;

Can someone explain what's happening on the right side of the equal sign?

OlivierLi
  • 2,798
  • 1
  • 23
  • 30
marblapas
  • 25
  • 4

6 Answers6

2

The pointer (or whatever it is) table is casted to the type "pointer to MyTable".

1

(MyTable*) is not a pointer. It's a c-style cast to the type " pointer to MyTable" .

table is presumably a pointer which is being converted by the cast.

Please not that c-style casts are not always your best option in c++ when dealing with OO design.

See : this question for details.

Edit:

The language tag on this question was c++ at first.

Community
  • 1
  • 1
OlivierLi
  • 2,798
  • 1
  • 23
  • 30
1

The text in parentheses is not a pointer, it is a type name. MyTable * is a pointer to MyTable.

A type name in parentheses is a cast.

A cast performs a conversion.

The cast (MyTable *) converts a value to a pointer to MyTable.

There are rules for converting pointers that can be somewhat tricky, so conversions like this might or might not result in valid code. The code MyTable *t = (MyTable *) table; is probably valid code if one of the following is true:

  • table is already a pointer to a MyTable, either directly or by having been properly converted in various ways.
  • table points to (enough) space allocated with malloc or another memory-management routine.
  • table is equal to NULL.

The code is probably not valid if:

  • table points to some kind of object other than a MyTable.
  • table is not a pointer.

There are some other specialized situations that are valid, but I am omitting the details since they are specialized. (These include integers that have been converted from pointers and conversions between pointers to aggregates and pointers to their first elements.)

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
0

It is casting table to a type of "pointer to MyTable".

MyTable is a class or struct, probably. A pointer to MyTable is a type of it's own (MyTable*).

noelicus
  • 14,468
  • 3
  • 92
  • 111
0

What is confusing you? Whatever table is, it is casted into a pointer to MyTable. This way, if the cast is possible, the assignment will be valid.

Mithrandir
  • 24,869
  • 6
  • 50
  • 66
0

MyTable t = (MyTable)table; Whenever this situation occurs think like this firstly on right: ()are evaluated first means table is converted to a pointer of type MyTable.look at following example

    when you say 
     float x;
     int y;
     x=y;//read below

when tou do x=y as type of y is int and you are assigning it to a float Here implici conversion is carried out which is

 x=(float)y;

Which is the way you are doing firstly table is converted to type MyTable* and then is assigned

OldSchool
  • 2,123
  • 4
  • 23
  • 45