+ 2

[solved] C++ derived class object as parameter of base class method?

Is there any way for a method of base class to accept ONLY derived class object as its parameter? My tries: 1. Directly write method to accept derived class const object by reference. Verdict: not working. Error: [derived class name] is not defined. 2. Play with references and full class definitions. Verdict: not working. Error: [either base or derived class name] is not fully defined, so cannot accept that type of parameters. Thinking of: 1. Doing it with multiple files and checking if a file is included. 2. Accept derived class object as base class object (by const reference, too).

24th Jan 2021, 12:02 PM
#0009e7 [get]
#0009e7 [get] - avatar
4 Answers
+ 4
Not sure why you'd want that kind of behaviour, but if I understood your requirements correctly, it is possible. Here is a single file demonstration: https://code.sololearn.com/c0h548DBS7C2/?ref=app
24th Jan 2021, 12:17 PM
Shadow
Shadow - avatar
+ 3
Just to make sure, but the const qualifier has no influence on it. What matters is the order of declaration, i.e. the base class only requires a forward declaration of the derived class for the method declaration, but the method definition needs a full definition of the derived class, hence the structure of the code.
24th Jan 2021, 3:16 PM
Shadow
Shadow - avatar
+ 1
Now I understood: method declaration can contain declared-only types. Thanks again!
24th Jan 2021, 3:56 PM
#0009e7 [get]
#0009e7 [get] - avatar
0
Oh, all I have to do is to declare the *const* method and write its code after derived declaration? I did not mind to make the method const... Anyway, thanks a lot! If everything with the code will be fine, I will try to make it public, so you can see why I needed that.
24th Jan 2021, 3:01 PM
#0009e7 [get]
#0009e7 [get] - avatar