I've got an abstract base with extremely minimal functionality, and several classes that inherit it. So for example...
class AbstracBasetClass
{
};
class ClassA : public AbstracBasetClass
{
public:
int numA;
};
class ClassB : public AbstracBasetClass
{
public:
int numB;
};
class ClassC: public AbstracBasetClass
{
public:
int numC;
};
class AbstracBasetClass
{
};
class ClassA : public AbstracBasetClass
{
public:
int numA;
};
class ClassB : public AbstracBasetClass
{
public:
int numB;
};
class ClassC: public AbstracBasetClass
{
public:
int numC;
};
To copy to clipboard, switch view to plain text mode
For the sake of simplicity each of the members is an int, but in my implementation they may be completely different and unrelated.
Now in my code, I have to instantiate one of these inherited classes and access the members, then do something with the class. So, I'll have something like this...
AbstracBasetClass* foo;
if (some condition)
{
foo = new ClassA();
foo->numA = 1;
}
else if (some other condition)
{
foo = new ClassB();
foo->numB = 2;
}
else if (some third condition)
{
foo = new ClassC();
foo->numC = 3;
}
// do something here with foo regardless of what its type is
AbstracBasetClass* foo;
if (some condition)
{
foo = new ClassA();
foo->numA = 1;
}
else if (some other condition)
{
foo = new ClassB();
foo->numB = 2;
}
else if (some third condition)
{
foo = new ClassC();
foo->numC = 3;
}
// do something here with foo regardless of what its type is
To copy to clipboard, switch view to plain text mode
Now this is perfectly valid of course, since foo is a pointer to the abstract base class and I'm merely instantiating one of the inherited classes. The problem is when I try to access the member, the compiler complains that "class AbstractBaseClass has no member named" and the member name in question. So instead, I have to do something like
foo = new ClassA();
((ClassA*)foo)->numA = 1;
foo = new ClassA();
((ClassA*)foo)->numA = 1;
To copy to clipboard, switch view to plain text mode
which works, but looks ugly and clunky.
I could just declare foo within each if block, but then the part at the end where I "do something with foo" fails, because the compiler says that foo isn't defined.
I'm wondering if there's any way around this, or is this it?
Bookmarks