Using an ABC object as a class member

Hi

I'd like to write a class which has a member variable which is an object of a type which inherits from an abstract base class (ABC). I understand that an ABC cannot be directly instantiated and so cannot itself be a member variable but that you can have a pointer to an ABC object. I read about this here - https://stackoverflow.com/questions/9782055/can-an-abstract-class-be-member-of-other-concrete-class-as-composition-relations

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
lass ThingABC { 
    public:
        virtual void Serialise(ostream& out)  = 0; 
        virtual void Deserialise(istream& in) = 0;
};

class MyThing : public ThingABC{
    
    private:
        int someOtherMember = 0;
    
    public:
        MyThing(int num) : someOtherMember(num) {}

        void Serialise(ostream& out) {
            out << someOtherMember;
        }
        
        void Deserialise(istream& in) {
            in >> someOtherMember;
        }
        
        int getSOM() {
            return someOtherMember;
        }
        
};


class ThingHolder {
    private:
        ThingABC* thing; // a pointer as ThingABC cannot be directly instantiated
        string nm = "thing";
    
    public:
        ThingHolder(ThingABC* newThing) : thing (newThing) {}
        
        ThingABC* getThing() const {
            return thing;
        }
        
};


int main()
{

    ThingHolder thingholder(new MyThing(4322));
    
    std::cout << thingholder.getThing() -> getSOM();
}


This produces the following error:


main.cpp: In function ‘int main()’:
main.cpp:57:44: error: ‘class ThingABC’ has no member named ‘getSOM’
     std::cout << thingholder.getThing() -> getSOM();
                                            ^~~~~~


ThingABC has no member named getSOM() but its subclass MyThing does. Do I need to cast ThingABC* to MyThing*? If so, how do I do this?

Thanks
Last edited on
If you want to use polymorphism, you would have getSOM() be a virtual function in the base-class and override it in the MyThing class.
Then, you can call the function through a base-class pointer or reference, and have it perform sub-class behavior.

If you are going to have other sub-class with different variables, you should perhaps rename your getX function to something less specific. The issue is your example is very abstract (what exactly is a "ThingHolder"? What is the purpose of this design?), so it's hard to see the kind of design this is supposed to become. You can use casting as a workaround, but if you're not careful you can break things. static_cast<MyThing*>(thingholder.getThing())

PS: When making minimal examples like you did above, please also add the stuff at the top like #includes, usings, etc. so that people on the forum can click to run your code without having to manually edit it.
Last edited on
Topic archived. No new replies allowed.