0

I am trying to use typeid() but i keep getting an error im not sure why.

void RandomAttributes(Shape * S)
{

// pointer need for down casting
MyTriangle * triPtr;
MyRect * rectPtr;
MyCircle * circPtr;

//downcast base class pointer to derived class pointer
if (typeid(*S).name == "MyTriangle")
{
    triPtr = dynamic_cast<MyTriangle *>(S);

    // reset the rectangle object to some known, legal values
    triPtr->SetPosition(p);
    triPtr->SetLength(S->GetWindowHeight() / 10);

}
else if (typeid(S).name == "MyRect")
{
    rectPtr = dynamic_cast<MyRect *>(S);

    // reset the rectangle object to some known, legal values
    S->SetPosition(p);
    rectPtr->SetLength(S->GetWindowHeight() / 10);
    rectPtr->SetWidth(S->GetWindowWidth() / 10);
}
else
{
    circPtr = dynamic_cast<MyCircle *>(S);

    circPtr->SetPosition(p);
    circPtr->SetRadius(S->GetWindowHeight() / 10);
}
}

a shape (base class) pointer is being passed into this function which could be pointing to a Mytriangle, Mycircle, or MyRect Object. I believe dereferenceing the pointer should be working but I guess not.

ex. typeid(*S).name

I already tried S, *S, and &S. So whats left??

Alvaromon
  • 190
  • 2
  • 16
  • Don't compare `char*` strings with `==`, and don't use the implementation-defined `type_info::name` for anything important. – Davis Herring Sep 24 '17 at 05:07
  • 3
    `if (typeid(*S) == typeid(MyTriangle))` is a far more reasonable test. ;) – enhzflep Sep 24 '17 at 05:08
  • Wow that worked thanks. so what did i do wrong @enhzflep – Alvaromon Sep 24 '17 at 05:13
  • 1
    @enhzflep `name` returns a `char*`, i.e. a pointer representing a C-style null-terminated string. You don't compare `char *` for equality to a string by using `==`. That is the job of `strcmp` or similar function. – PaulMcKenzie Sep 24 '17 at 05:15
  • @PaulMcKenzie - Yes, that's correct. Why are you telling _me_ this? – enhzflep Sep 24 '17 at 05:20
  • @Alvaromon - See Paul's comment. – enhzflep Sep 24 '17 at 05:21
  • @enhzflep Sorry, had put the wrong response name in the comment. – PaulMcKenzie Sep 24 '17 at 05:22
  • @PaulMcKenzie - no dramas. Thought that was likely to be the case, but certainty seemed cheap to obtain. :) – enhzflep Sep 24 '17 at 05:24
  • The results of `typeid` are implementation defined. You can compare them, but not expect them to have specific values (or contain specific strings, like `"MyTriangle"`). Also the name member is a `char *`, so should not be compared using `==`. In any event, `dynamic_cast(S)` will give a `NULL` pointer if `S` is not a pointer to `MyRect`. – Peter Sep 24 '17 at 06:05

0 Answers0