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 */ }
};

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 }
};

1

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

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