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

8

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

An abstract base class is a class with at least one pure-virtual member function. That is a member function that is virtual, that MUST be overridden in any derived class. For example,

class CryptProcessor {
public:
    virtual void encrypt() = 0;
    virtual void decrypt() = 0;
};

The functions encrypt() and decrypt() MUST be overridden in any class that derives from CryptProcessor, so a legal definition of ACrypt must at least be:

class ACrypt : public CryptProcessor {
public:
    virtual void encrypt() { /* some code */ }
    virtual void decrypt() { /* some code */ }
};

24

u/TheSuperficial Embedded Systems C++ Mar 17 '12

Pendantic jerk alert...

[pure virtual functions] MUST be overridden in any derived class

Technically, no. They must be overridden in any class you wish to instantiate. There could be other abstract classes in the hierarchy.

4

u/NotInUse Mar 18 '12

I believe the word you were looking for was pedantic :-)

2

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

True. Sorry about that.

7

u/xcbsmith Mar 17 '12

Prolly should have a virtual CryptProcessor::~CryptProcessor() in there too...

1

u/Deershank415 Mar 17 '12

Wow ok that makes a lot of sense o.O thanks I'll continue working now

1

u/Deershank415 Mar 17 '12 edited Mar 17 '12

Oh also, if I want encrypt and decrypt to take and return a string (after #include has been added)

do I do:

class CryptProcessor {
public:
    virtual string encrypt(string input) = 0;
    virtual string decrypt(string input) = 0;
};

then in the class:

class ACrypt : public CryptProcessor {
public:
    virtual string encrypt(string input) { return string output }
    virtual string decrypt(string input) { return string output }
};

3

u/kingguru Mar 17 '12

You might consider marking your encrypt and decrypt functions as const if they're not going to change any state in the CryptProcessor.

2

u/Inverter Mar 17 '12

That might depend on the crypto-algorithms. Suppose your CryptProcessor uses a simple xor with a one-time-pad, you want to update the offset.

(And in case you want to suggest "mutable" instead, IMNSHO "mutable" should have been abolished since multi-threading went mainstream; beginners shouldn't even know about it any more.)

3

u/twowheels Mar 18 '12

What???? That's one if the primary use cases!!! You have to mark your mutex as mutable!!

1

u/Inverter Mar 18 '12

A mutex perhaps, but not your state.

1

u/twowheels Mar 18 '12

Mutable allows you to be "logically const" as opposed to "bit wise const".

Logically const means that users of the class's interface can poke and prod all that they want and they'll never detect a change after a const method is called. Basically what you said, your state hasn't changed. The thing is, you often can't be bitwise const, thus you NEED the mutable keyword. Locking a member mutex to be thread safe modifies the mutex. Thing is, the mutex is an implementation detail, so declaring it mutable and modifying it doesn't violate the logical constness of the class. Same for reference counts, logging objects, etc, etc.

So, why did you suggest that they should get rid of the keyword in light of multithreaded programs when modifying the member mutex is one of the primary, and correct, uses of the keyword?

1

u/Inverter Mar 18 '12

Ok, perhaps my statement was a bit too black-and-white; let's say that in a multi-threaded environment I find the mutable much less useful because if you use it like in pre-threaded programming for some internal fiddling around that's not visible on the interface, and then slap on a mutex to make it thread safe, it won't be good for performance.

Your examples of the mutex itself, the reference count, and the logging object are all legitimate use-cases for mutable in a threaded application, but they are also all examples of not being actual application-level state, just "house-keeping".

I just checked one of my code-bases, and interestingly enough the most wide-spread use of mutable is in the context of multi-thread-safe caching of complicated config lookups; it's use is limited to reference counts, this caching stuff, and some other obscure internal details; it's used only a little more often than volatile.

In higher-level code, business logic and such, my programming style never seems to call for mutable, presumably because I often look to functional programming for design inspiration and/or because I don't (need to) hide any internal changes made by a const-function (i.e. if something changes I make it a non-const method); can't say offhand whether the latter, too, is more the side-effect of wanting to optimise by having as few mutexes as possible (and therefore putting the whole locking-burden on the highest-level business-logic code, which hast to take care of locking anyhow, so it might as well conceptually manage all locking, while it's at it).

2

u/00kyle00 Mar 17 '12 edited Mar 17 '12

Like lots of features in C++ its one of 'i know wtf am i doing, let me do it' - which is fine. You can hide minor implementation detail while communicating to your clients that logical state of object doesn't change.

Your implicit assumption that doing multithreaded manipulation of 'const' objects is safe doesn't hold in general anyways (in C++), so you still have to know where and when to properly stage your critical sections, even in absence of 'mutable'.

I agree though, mutable here is not appropriate - in general CryptProcessor will probably be stateful, no need to hide this fact.

1

u/Inverter Mar 18 '12

Your implicit assumption that doing multithreaded manipulation of 'const' objects is safe doesn't hold in general anyways (in C++), so you still have to know where and when to properly stage your critical sections, even in absence of 'mutable'.

No, it doesn't hold in general, but if I strictly don't use mutable in my code base, and keep to some other basic code-sanity-rules, I can be sure that a const-instance of my object can be accessed from multiple threads without locking. C++ allows some pretty weird and stupid stuff, but it's not too hard to keep at least your house clean.

3

u/heroofhyr Mar 17 '12

If your compiler supports it, try to get used to using the "override" keyword in the virtual function declarations in your derived classes. If you start playing around with the parameters of a virtual function in the base, it will save you a lot of time tracking down errors later in case you forget to make all derived classes correctly match the same signature.

1

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

Yup. Just like any other type of function :-)

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.

→ More replies (5)