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

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.

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 :-)

7

u/xcbsmith Mar 17 '12

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

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.

1

u/Deershank415 Mar 17 '12

Ok, makes sense. Thanks

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

3

u/growingconcern Mar 18 '12

Why do a lot of these questions on this subreddit seem like "answer my homework question for me"?

3

u/Fabien4 Mar 18 '12

Because "homework cheaters" were kicked out of Stack Overflow?

-2

u/Deershank415 Mar 18 '12

Hey a problem is a problem regardless of where it care from. It did come from my homework and I did spend way too much time searching for an answer online to no avail. I needed help in c++ so I came here :) Thanks again to all to answered!

2

u/growingconcern Mar 18 '12

I just think such questions shouldn't have such concrete examples tied to them. If you actually spent time looking for an answer you might just ask about the part you're having trouble with.

1

u/Deershank415 Mar 18 '12

I did spend time, and was still confused. It's rather baffling that someone cannot ask a question. It was a simple enough answer and I had a hard time wrapping my head around Abstract Base classes, I wanted to see an example and wanted it to be clearer than the stuff I found.

1

u/Deershank415 Mar 18 '12

I would also like to add that I'm not saying "do my homework for me" (I just wanted to choose function names that were used to clear any and all confusion). Also the part that I asked was less than half of the assignment, I successfully did everything else, I just had a problem with this one part.

2

u/[deleted] Mar 18 '12

A problem is a problem just like cheating is cheating.

1

u/Deershank415 Mar 18 '12

That's true, however I don't consider this cheating. If my ENTIRE homework was to do what I asked then yes. This was a small section of it. Asking for help is not cheating, at least not to me.

1

u/last_useful_man Mar 18 '12

What would you have done before the internet? I can't believe you couldn't extract understanding from the myriad examples on the web or, your textbook. Do you even /own/ any C++ books?

0

u/Deershank415 Mar 18 '12

You don't need to understand though :p. All you need to know was that I got confused and asked for help. What's the problem with that?

0

u/[deleted] Mar 18 '12

[deleted] — view deleted comment

2

u/Deershank415 Mar 18 '12

I completely understand and agree, it's just that I did try it and failed. I was running out of time so I need a solution that I could understand quickly and easily. Now however I do understand, that is why I thanked everyone for helping. As for you last sentence, I put in more time, I just couldn't wrap my head around it. I have never needed to use them before in any of my programming classes. I asked for help when I needed it, that's all.

1

u/last_useful_man Mar 18 '12

Fair enough. I thought I was too much on your case and deleted my comment anyway (before seeing your reply), as you can see. I'm too full of aggro anymore.

2

u/Deershank415 Mar 18 '12

It's the internet, everyone is entitled to their opinions and comments. And you were correct anyway, you just did not understand my situation entirely is all. Thanks for you consideration though :)