CS253

CS253: Software Development with C++

Spring 2018

Pure Virtual

See this page as a slide show

Pure Virtual

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: In function 'int main()':
c.cc:7:11: error: cannot declare variable 's' to be of abstract type 'Super'
c.cc:1:7: note:   because the following virtual functions are pure within 
   'Super':
c.cc:3:18: note:  virtual void Super::foo()

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.

Modified: 2017-02-23T16:44

User: Guest

Check: HTML CSS
Edit History Source
Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2015 Colorado State University
CS Building