Topic: Inheritance question
Author: "Rishi Dhupar" <rishid@gmail.com>
Date: Wed, 4 Apr 2007 10:08:52 CST Raw View
Is there anyway to determine and object type (base class or subclass)
during runtime?
For instance I have a function in the base class, I am trying to do
something like the pseudocode below. This feasible at all without
making a another virtual function for the base and child classes.
void foobar (int x)
{
if (this == base class)
// do something
else if (this == child class)
// do something
}
Thanks for any input.
RishiD
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]
Author: markus.moll@esat.kuleuven.be (Markus Moll)
Date: Wed, 4 Apr 2007 16:12:45 GMT Raw View
Hi
Rishi Dhupar wrote:
> Is there anyway to determine and object type (base class or subclass)
> during runtime?
Yes for polymorphic classes.
The following snippet:
-- snip --
#include <iostream>
#include <ostream>
#include <typeinfo>
using namespace std;
struct Base
{
virtual ~Base() {}
void f() { cout << (typeid(*this) == typeid(Base)) << endl; }
};
struct Derived : Base
{
};
int main()
{
Base b;
Derived d;
b.f();
d.f();
}
-- snip --
outputs:
1
0
But most of the time such techniques would be inferior or would be
considered worse style than virtual functions.
Markus
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]