Start New Discussion within our Software Development Community

Hello Daniweb!

I'm coding a small application and I've hit a road block. I've been using C++ for almost two years now, but to be honest, I hardly use dynamic polymorphism (i prefer static), and so with great embarrassment, I come here to ask this:

My code is basically structured like this. I have a base class that many derive from, and it has 'common' functions that are virtual (of course :P). Any ways, there is another common function, but in each of the sub classes, it has a different return type. Now, i thought that if i have a 'Base' pointer, that pointed to allocated subclasses, I could still access non virtual functions...but of course i can't...so my question is, what do you do in a situation like this?

// this is now my code is structured :D
#include <iostream>

class Base {
	public:
		virtual void Common() {} // a function common to all sub classes
};

class Class1 : public Base {
	public:
		int GetValue() { return 1; } // same as Class2 but int
};

class Class2 : public Base {
	public:
		char GetValue() { return '2'; } // same as Class1 but char
};

int main() {
	Base* b = new Base;
	b->Common(); // ok
	delete b;

	b = new Class1;
	*b->GetValue(); // error!
	delete b;

	b = new Class2;
	*b->GetValue(); // also error!
	delete b;

	return 0;
}

Thanks in advance :D

You need dynamic_cast. For example

(dynamic_cast<Class1*>(b))->GetValue()

will get you the value of 1 in your code.
Use the dynamic_cast to convert your Base * object to a Class1* type (essentially you're just moving down the class hierarchy hence you used dynamic_cast and "downcast" the object) and now that you have a full-fledged Class1 object you can access the GetValue() method. Same holds for the other Base * object except cast it to Class2*.

This article has been dead for over six months. Start a new discussion instead.