Abstraction in C++ (original) (raw)

Last Updated : 27 Feb, 2026

Abstraction is the concept of exposing only the essential features of an object while hiding the internal implementation details.

Abstract Classes

Abstraction is mainly achieved using abstract classes and pure virtual functions. These define a common interface for derived classes while leaving the actual implementation to them.

#include #include using namespace std;

// Abstract base class as there is a // pure virtual method class Shape{ protected: string color;

public: Shape(string color) : color(color){}

// Abstract or Pure virtual method
virtual double area() = 0;

// Concrete method
string getColor(){
    return color;
}

virtual ~Shape() {}

};

// Derived class: Rectangle class Rectangle : public Shape { double length, width;

public: Rectangle(string color, double length, double width) : Shape(color){ this->length = length; this->width = width; } double area() override { return length * width; } };

int main() { Shape* s = new Rectangle("Yellow", 2, 4);

cout<<"Rectangle color is "<<s->getColor()<<" and area is : "<<s->area()<<endl;
return 0;

}

`

Output

Rectangle color is Yellow and area is : 8

**Explanation:

Full Abstraction - Interfaces

In C++, a class can act as an interface if it contains only pure virtual functions and no data members or implemented methods. This enforces that all derived classes must implement every function, achieving full control abstraction. Interfaces are useful when multiple classes need to share a common interface without sharing implementation.

C++ `

#include using namespace std;

// Pure Abstract Class acting as an Interface class Printable { public: virtual void print() = 0; // pure virtual function virtual void scan() = 0; // pure virtual function

// Virtual destructor is a good practice for base classes
virtual ~Printable() {}

};

// Derived class must implement all functions class Document : public Printable { public: void print() override { cout << "Printing document..." << endl; } void scan() override { cout << "Scanning document..." << endl; } };

// Another derived class implementing the same interface class Photo : public Printable { public: void print() override { cout << "Printing photo..." << endl; } void scan() override { cout << "Scanning photo..." << endl; } };

int main() { // Base class pointer pointing to derived objects Printable* p1 = new Document(); Printable* p2 = new Photo();

// Call interface functions - runtime polymorphism
p1->print();
p1->scan();

p2->print();
p2->scan();

// Free memory
delete p1;
delete p2;

return 0;

}

`

Output

Printing document... Scanning document... Printing photo... Scanning photo...

**Explanation: