Labs ICT
Pro Login

Abstraction

1 min read | C++ Tutorial

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

Abstraction

Abstraction hides implementation details and exposes only essential features. In C++, use abstract base classes containing at least one pure virtual function.

Pure Virtual Functions

A pure virtual function has no body and is declared with = 0. Any class with a pure virtual function becomes abstract and cannot be instantiated directly. Derived classes must override all pure virtual functions to become concrete.

#include <iostream>
using namespace std;

class Instrument {
public:
  virtual void play() = 0;
};

class Guitar : public Instrument {
public:
  void play() override {
    cout << "Strumming guitar\n";
  }
};

class Piano : public Instrument {
public:
  void play() override {
    cout << "Playing piano\n";
  }
};

int main() {
  Instrument* inst1 = new Guitar();
  Instrument* inst2 = new Piano();
  inst1->play();
  inst2->play();
  delete inst1;
  delete inst2;
  return 0;
}