Object casting question

Good Morning,

I have two classes as follows:

class A
{
public:
A();
~A();
CString function1(void);
private:
CString ABC(void);
};


class B
{
public:
B();
~B();
CString function1(void);
private:
CString XYZ(void);
};

In each class, function1 makes a call to the private function.
I would like to be able to use a model type to choose between instantiating an object based upon Class A or Class B.

Is this possible? function1 is my interface.
How do I create a single pointer that can run function1, regardless of the class it comes from>

Thanks...
You'd have to create a base class with a virtual function function1 (with exactly the same signature as in A and B), have both A and B inherit from that base class.

Then when you instantiate either an A or B, you have to make a reference or pointer to the base class.

This is called polymorphism and is explained further here: http://www.cplusplus.com/doc/tutorial/polymorphism/
Thank you shadowmouse. That works for me. I reworked to:
class BaseClass
{
public:
virtual CString function1(void)=0;
};

class A : public BaseClass
{
public:
A();
~A();
CString function1(void);
private:
CString ABC(void);
};

class B : public BaseClass
{
public:
B();
~B();
CString function1(void);
private:
CString XYZ(void);
};
When I instantiate, I do the following:
BaseClass *b;
if ( modelType == "A")
b = new A;
else if ( modelType == "B")
b = new B;
b->function1();

Thanks for your help!

Topic archived. No new replies allowed.