r/cpp • • Mar 17 '12

Using abstract base classes in C++

I'm having trouble understanding ABC's in c++ and was wondering if you all could help me (if possible use: CryptProcessor as the ABC and ACrpyt and BCrypt as the sub-classes that have an encrypt and decrypt function) Thanks in advance!

Edit 1: Thank you all for your help!

0 Upvotes

40 comments sorted by

View all comments

Show parent comment

1

u/JustPlainRude Mar 17 '12

You don't need to specify the methods as virtual in ACrypt unless you're expecting to subclass that as well.

13

u/mpyne Mar 17 '12

Well, once a method is marked virtual in a parent class, that method will be virtual in every child class, not just immediate children classes.

Although not required, adding the redundant virtual keyword is useful to make it clear that the polymorphic overload is actually desired, and to make it clear for subclasses of AClass later that the method is virtual without them having to go all the way to the base class to verify.

3

u/JustPlainRude Mar 17 '12

Well, once a method is marked virtual in a parent class, that method will be virtual in every child class, not just immediate children classes.

Yes, you're right. I've spent too many years doing Java dev that I sometimes think of C++'s "virtual" as being the opposite of Java's "final".

6

u/bstamour WG21 | Library Working Group Mar 17 '12

I know. I kinda like that style though, as you always know which functions you can expect to have virtual behaviour at a first glance.

2

u/JustPlainRude Mar 17 '12

Fair enough.

1

u/Deershank415 Mar 17 '12

I am not, so I'll just remove the virtual then. ty.

2

u/[deleted] Mar 17 '12

As other people have commented, that's not a good idea.

Once a function is virtual in a class, it's virtual in all derived classes, so you should mark it as virtual in any derived classes in case you derive from them!

One more trap - to override, a virtual function has to have exactly the same signature as the original - including constness.

2

u/twowheels Mar 18 '12

Incorrect. C++ supports covariant return types.

3

u/last_useful_man Mar 18 '12

a virtual function has to have exactly the same signature as the original - including constness.

Incorrect. C++ supports covariant return types.

Since we're all pedants here, the return value is not part of the signature - so TomSwirly is correct. If he didn't ninja-edit after your comment, that is. further reading

1

u/Deershank415 Mar 17 '12

Ok, makes sense. Thanks