Abstract classes

Greetings. I have an abstract class, call it C, with two subclasses C1 and C2. In classes C, C1, and C2, there is a virtual method, HasProp1. What I would like to do is to be able to do something like

1
2
3
4
5
6
7
   ...
   vector<C*> CVec;
   CVec.push_back(new C1(arg1, arg2));
   CVec.push_back(new C2(arg1, arg2));
   ...
   bool a0 = CVec[0]->HasProp1(argx1, argx2);
   bool a1 = CVec[1]->HasProp1(argx1, argx2, argx3);


I know that this is illegal. My current solution is to add an additional (virtual) method, SetParam, to C, C1, and C2, and do the following:

1
2
3
4
   ...
   bool a0 = CVec[0]->HasProp1(argx1, argx2);
   C_Vec[1]->SetParam(argx3);
   bool a1 = CVec[1]->HasProp1(argx1, argx2);


However, this strikes me as extremely sloppy. Is there a better way to do something like this? (The actual code is much more complicated). Thanks.
Last edited on
Will your first option not work if you overload HasProp1 in C?
Sorry. C1 and C2 both also have HasProp1. I have edited the original post accordingly.

As to whether the first option should work, note that CVec is a pointer to C, and that CVec[0] and CVec[1] have a static class of C*, although their dynamic classes are C1 and C2 respectively. Any message sent to an object with static class C* must be able to be understood by C, even if the message would be understood by C1 or C2. Thus, C1::HasProp1 and C2::HasProp1 must have the same type signatures, and the first option is illegal.

My original question remains.
Last edited on
He means something like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct C
{
    virtual bool  HasProp1(p1_t p1, p2_t p2) { throw UnsupportedOperationEx;};
    virtual bool  HasProp1(p1_t p1, p2_t p2, p3_t p3) { throw UnsupportedOperationEx;};
}

struct C1 : C
{
    virtual bool  HasProp1(p1_t p1, p2_t p2, p3_t p3) override { /*do something*/ };
}

struct C2 : C
{
    virtual bool  HasProp1(p1_t p1, p2_t p2) override { /*do something*/ };
}
Alternatively you can drop third argument instead of throwing an exception

I must note that if you ever need to go down on inheritance tree and choose action based on real type (as opposed to object chosing what to do themselves), you are most likely did your architecture wrong.

If in your case it is impossible to switch array indices on lines 6 and 7, then saving objects as pointers to common type is useless.
Topic archived. No new replies allowed.