Base class as parameter

I have run into a problem which is mostly just an annoyance. I need to know if i can have pass a derived class to a function which has the base class as its parameter. For example i have been creating a program but i have a function which needs to work for multiple classes all derived from the BaseObject class

Code (this isn't actually my code but it is an example)
1
2
3
4
5
6
class folder : public BaseObject
{}


class BaseObject
{void function(BaseObject B)}


how would i get the following to work:

function(folder)
Could you give the concrete example of what you are trying to do here? You could have each class overload that function for the different parameters, or use a pointer if it only needs to operate on fields inside BaseObject, but I'm not sure if that is appropriate for your use case.
the function is for collision i want to have the collision be usable with all of BaseObject's derived classes
Make it take a polymorphic pointer (probably as a reference):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class BaseObject {
    public:
        void function(BaseObject& b) {
            // do something with 'b' - note that 'b' COULD be a folder,
            // but you don't know until the program is run.
        }
};

class Folder : public BaseObject {};

int main() {
    BaseObject obj1;
    BaseObject obj2;

    obj1.function(obj2);

    Folder f;
    obj1.function(f);

    return 0;
}
Last edited on
Topic archived. No new replies allowed.