daniel_a
daniel_a

Reputation: 25

Strange behaviour of the typeid operator -return FALSE always

This is my part of my code. The question is why using this line return FLASE and i can't get in to his block: i'm trying to check if my item type is equals to the son. It's suppose to return true. I see in the debugging it's true also.

if ((typeid(Candy) == typeid(sArray[0])) && (typeid(Candy) == typeid(&item)))

this is my code:

bool Customer::isExistItem(SweetItem& item){

if (Itemsize == 0){
    sArray = new SweetItem*[Itemsize + 1];
    sArray[Itemsize] = &item;
    Itemsize++;

    if ((typeid(Candy) == typeid(sArray[0])) && (typeid(Candy) == typeid(&item))){
        Candy* help1 = dynamic_cast <Candy*> (sArray[0]);
        Candy* help2 = dynamic_cast <Candy*> (&item);

        if (*help1 == *help2){ //The first item in the basket!
            double payment = 0;
            payment += help1->getPrice();
            totalPayment(payment);
        }

        return TRUE;
    }

    else if ((typeid(Cookie*) == typeid(sArray[0])) && (typeid(Cookie*) == typeid(&item))){
        Cookie* help1 = dynamic_cast <Cookie*> (sArray[0]);
        Cookie* help2 = dynamic_cast <Cookie*> (&item);

        if (*help1 == *help2){ //The first item in the basket!
            double payment = 0;
            payment += help1->getPrice();
            totalPayment(payment);
        }

        return TRUE;
    }

    else if ((typeid(IceCream*) == typeid(sArray[0])) && (typeid(IceCream*)   == typeid(&item))){
        IceCream* help1 = dynamic_cast <IceCream*> (sArray[0]);
        IceCream* help2 = dynamic_cast <IceCream*> (&item);

        if (*help1 == *help2){ //The first item in the basket!
            double payment = 0;
            payment += help1->getPrice();
            totalPayment(payment);
        }

        return TRUE;
    }

    else if ((typeid(Cookielida*) == typeid(sArray[0])) &&         (typeid(Cookielida*) == typeid(&item))){
        Cookielida* help1 = dynamic_cast <Cookielida*> (sArray[0]);
        Cookielida* help2 = dynamic_cast <Cookielida*> (&item);

        if (*help1 == *help2){ //The first item in the basket!
            double payment = 0;
            payment += help1->getPrice();
            totalPayment(payment);
        }

        return TRUE;
    }
}

this is my == operator that looks ok:

bool Customer::operator ==(const SweetItem& other) const{
for (int i = 0; i < Itemsize; i++){
    if (sArray[i] != &other)
        return FALSE;
}
return TRUE;

}

please take a look at my code.

Upvotes: 1

Views: 82

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254721

The type of both sArray[0] and &item is a SweetItem* pointer, which is never the same as a Candy object.

I guess you want typeid(*sArray[0]) and typeid(item), to examine the dynamic type of the object rather than a more generically typed pointer.

Upvotes: 1

Related Questions