Is is possible to get base class type in a class hierarchy?
For example:
struct A{};
struct B{} : public A;
struct C{} : public B;
I want some template that will have typedef Base<T>::Type
inside like this:
Base<A>::Type == A
Base<B>::Type == A
Base<C>::Type == A
Is this possible? What about the case when I have multiple inheritance?
The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. A derived class can have only one direct base class. However, inheritance is transitive.
You can derive a class from any number of base classes. Deriving a class from more than one direct base class is called multiple inheritance. The order of derivation is relevant only to determine the order of default initialization by constructors and cleanup by destructors.
What is a Base Class? In an object-oriented programming language, a base class is an existing class from which the other classes are determined and properties are inherited. It is also known as a superclass or parent class.
Yes, struct can inherit from class in C++. In C++, classes and struct are the same except for their default behaviour with regards to inheritance and access levels of members.
Classes in C++ can have more than one base class, so there's no sense in having a "get me the base" trait.
However, the TR2 additions include new compiler-supported traits std::tr2::bases
and std::tr2::direct_bases
, which returns an opaque type list of base classes.
I'm not sure whether this will make it into C++14, or whether it'll be released independently, but GCC already seems to support this.
I think std::is_base_of
can help you
#include <type_traits>
std::is_base_of<B, D>()
If D is derived from B or if both are the same non-union class, provides the member constant value equal to true. Otherwise value is false.
You can use it to check if a class is base class of another or not :
std::is_base_of<A, A>() // Base<A>::Type == A
std::is_base_of<A, B>() // Base<B>::Type == A
std::is_base_of<A, C>() // Base<C>::Type == A
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With