Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

inheritance question

Status
Not open for further replies.

zildjohn01

Programmer
Sep 6, 2005
10
US
hi, i would like to be able to tell which type of derived class a base class is. pseudocode:

Code:
// pseudocode.cpp
#include <stdio.h>

class Base{};
class Derived : public Base {};

void test(Base &cls) {
	if(typeof(cls) == typeof(Derived))
		printf("cls is 'Derived'\n");
	else if(typeof(cls) == typeof(Base))
		printf("cls is 'Base'\n");
}

void main() {
	Base b;
	Derived d;
	test(b);
	test(d);
	printf("done\n");
}

any ideas if this is possible in standard c++ ??
 
The whole point is that the function Test doesn't need to know how Base is instantiated.

/Per
[sub]
www.perfnurt.se[/sub]
 
If the Base is not a polymorphic class (no virtual functions), no matter what's a class of test() argument (you can't access derived class members via cls reference.
Another case (it works in VC++ 6 etc):
Code:
class Base{public:virtual ~Base(){}};
class Derived : public Base {};
...
void test(Base &cls) 
{
  Derived d;
  const type_info& tyb = typeid(cls);
  const type_info& tyd = typeid(d);
  cout << (tyb==tyd?"Derived":"Base") << endl;
}

int main() { // not void main()!
    Base b;
    Derived d;
    test(b);
    test(d);
    cout << "done" << endl;
    return 0;
}
Don't forget to turn on RTTI support...
 
A third case that is kind of cheating, but anyway:

Code:
// Forwvard declaration
class Derived;  

class Base
{
public:
  Base() {}
  virtual ~Base() {}

  Derived* getDerived() { return NULL; }
};

class Derived : public Base
{
	public:
	Derived():Base() {}
	virtual ~Derived() {}

	Derived* getDerived() { return this; };

	void derivedOnlyMehtod() {};
};


void test(Base& base)
{
	Derived* d = base.getDerived();
	if (d!=NULL) d->derivedOnlyMethod();
}

/Per
[sub]
www.perfnurt.se[/sub]
 
I've never found typeid to be very reliable in VC 6.0. If I have 2 classes derived from the same base and I say:
Code:
if ( typeid( derived1 ) == typeid( derived2 ) )
it will always be true, because for some stupid reason the typeid always returns the type of the base class. :(
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top