CS253: Software Development with C++

Spring 2018

Pure Virtual

See this page as a slide show

CS253 Pure Virtual

Example

Here’s some ugly syntax:

class Super {
  public:
    virtual void foo() = 0;
};

int main() {
    Super s;
    s.foo();
    return 0;
}
c.cc:7: error: cannot declare variable 's' to be of abstract type 'Super'

Since Super contains a pure virtual function, it cannot be instantiated. It is an Abstract Base Class, or ABC. It’s similar to an interface in Java.

Example

class Super {
  public:
    virtual void foo() = 0;
};

class Sub : public Super {
  public:
    void foo() {
        clog << "Aquaman or the Sub-Mariner?  You decide!\n"
             << "🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟\n";
    }
};

int main() {
    Sub s;
    s.foo();
    return 0;
}
Aquaman or the Sub-Mariner?  You decide!
🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟

Sub has no pure virtual functions remaining, so it can be instantiated.

User: Guest

Check: HTML CSS
Edit History Source

Modified: 2018-04-24T16:55

Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2018 Colorado State University
CS Building