it would give a compilation error.
i am more of looking for runtime output.... i did try with dynamic_cast though... alas it gives me a compilation error.
template <class Super, class Sub>
struct AssertSuperSubClass
{
~AssertSuperSubClass()
{
Super * s = (Sub *) 0;
}
};
class A {};
class B : public A {};
class C {};
int main()
{
AssertSuperSubClass<A, B>(); // ok!
AssertSuperSubClass<A, C>(); // error!
return 0;
}
But apparently this is not what you want.
What exactly are you trying to achieve?
But i was wondering if, is there some kind of provision in the language itself to know that a given object belongs to a class which is
inherited from some other know class.
In c++ there are well known associations from base class to derived class , but i havent come across something which gives association in other direction. i am not sure if this is needed at all.
i am looking answers for these question -
is there some kind of such association exists?
can this be achieved during run time?
Yes your program does answer my question, if compilation error is accepted.
If b inherits a member form a, it will have a different size. When compiling the code, the sizeof() function will evaluate to a different value. If there are no inherited data members, though,then there will be no size difference, making this problem trickier.
#include <iostream>
template <class Super, class Sub>
struct IsSuperSubClass
{
staticbool ConversionTest(const Super *) { returntrue; }
staticbool ConversionTest(constvoid *) { returnfalse; }
staticconst Sub * p;
staticconstbool VALUE;
};
template <class Super, class Sub>
const Sub * IsSuperSubClass<Super, Sub>::p = 0;
template <class Super, class Sub>
constbool IsSuperSubClass<Super, Sub>::VALUE =
IsSuperSubClass<Super, Sub>::ConversionTest(p);
class A {};
class B : public A {};
class C {};
int main()
{
std::cout << IsSuperSubClass<A, B>::VALUE << std::endl;
std::cout << IsSuperSubClass<A, C>::VALUE << std::endl;
return 0;
}
Though, I think this is not what you want either.
If I understand correctly, what you want is reflection.
C++ doesn't have a built-in reflection mechanism.
The most straightforward way to do this is to provide
that information yourself, in order to be able to use it later:
@L B, i am not sure if sizeof operator is foolproof way of identifying the objects inheritance nature towards multiple known classes.
@m4ster r0shi,
Yes, indeed i was looking for something similar to reflection.
since there are no such in-built facility available in c++, self implementation is the way forward.
thanks for the link. my question is duely answered.