How to check if the obj is actually YourClass instance, but not YourClass inherited classes instance?Code:void test(YourClass *obj);
Should we use RTTI here?
Thanks in advance. :-D
Printable View
How to check if the obj is actually YourClass instance, but not YourClass inherited classes instance?Code:void test(YourClass *obj);
Should we use RTTI here?
Thanks in advance. :-D
Why would you want to? It's possible, sure, but usually it's expensive and doesn't need to be done (alternative solutions are better).
It seems incorrect if it returns true while obj is a YourClass derived object, isn't it?Code:bool operator == (YourClass *obj)
Tried,
but it doesn't work that way.Code:dynamic_cast
If I'm not mistaken you can use typeid here (naturally you can dynamic_cast derived objects to base).
Whatever it is that you are doing.Code:#include <iostream>
#include <typeinfo>
struct Base
{
virtual ~Base() {}
};
struct Derived: Base {};
void test(Base* p)
{
std::cout << (typeid(*p) == typeid(Base)) << '\n';
}
int main()
{
Base b;
Derived d;
test(&b);
test(&d);
}
To make our program reliable and correct.
Please look at reply #3.
This is insane, in contrast to efficiency I think.. Whatever..
Thanks anon,..
Sorry, I'm just lazy to type: const YourClass &obj on my phone keypad.
Usually I just use my global macro:
Code:CR(YourClass, obj)
Seems doesn't work like you said.Code:class A {
public:
virtual void a() const { cout << "A::a()" << endl; }
};
class B : public virtual A {
public:
virtual void a() const { cout << "B::a()" << endl; }
};
void test(const A &a) {a.a();}
test(A()); //A::a()
test(B()); //B::a()
If you pass by value only what the objects have in common will be copied.
Either way you should document that your code doesn't address the slicing problem and it is invalid to pass Derived objects to test, or whatever.
I think you are doing something wrong in your code if a derived class is generally valid, but can't be used where the base-class can be used. You either haven't made something virtual that should be virtual, or you are doing something else quite wrong.
Or you should forbid inheritance (which I think there is a common pattern for how you do that, but I couldn't be bothered to searching long enough to find it - I'm sure someone else is able to show it, if need be).
--
Mats
It's called the named constructor idiom.Quote:
Or you should forbid inheritance (which I think there is a common pattern for how you do that, but I couldn't be bothered to searching long enough to find it - I'm sure someone else is able to show it, if need be).