Code Skiller logoCB Logo
Logo LearnLearnLogo PracticePracticeLogo HireHireLogo IDEIDE

Abstraction

User image

Published by

sanya sanya

Published at: 6th Aug, 2023
2.24 mins read

Abstraction is the process of representing essential features of an object while hiding the unnecessary details, allowing you to focus on the functionality you need. It allows you to create simple and clear interfaces for complex systems.

- Abstract classes are classes that cannot be instantiated and may contain one or more pure virtual functions.

- Pure virtual functions make a class abstract and must be overridden in derived classes to make those classes concrete.

Abstract classes and interfaces

Abstract classes and interfaces are concepts commonly used in object-oriented programming to achieve abstraction and define contracts for classes. Both are used to declare methods without providing their implementation, leaving it to the derived classes to implement those methods.

1. Abstract Class:

- An abstract class is a class that cannot be instantiated. It is meant to serve as a base class for other classes, providing a common interface and defining some common behavior.

- Abstract classes may have both regular (concrete) methods with implementations and pure virtual methods, which are declared using the ‘virtual’ keyword and have no implementation.

- Derived classes that inherit from an abstract class must implement all the pure virtual methods to become concrete classes.

- Abstract classes allow code reuse by providing a common interface for a group of related classes.

Example:

class Shape {

public:

// Pure virtual method

virtual void draw() = 0;

// Regular method with implementation

void displayInfo() {

cout << "This is a shape." << endl;

}

};

class Circle : public Shape {

public:

void draw() override {

cout << "Drawing a circle." << endl;

}

};

class Square : public Shape {

public:

void draw() override {

cout << "Drawing a square." << endl;

}

};

2. Interface:

- An interface is a class that contains only pure virtual methods and no data members or method implementations. It defines a contract that other classes must follow.

- Classes that implement an interface must provide implementations for all the methods declared in the interface.

- Interfaces are useful for creating a common behavior that unrelated classes can adhere to.

Example:

class Printable {

public:

virtual void print() = 0;

};

class Document : public Printable {

public:

void print() override {

cout << "Printing a document." << endl;

}

};

class Image : public Printable {

public:

void print() override {

cout << "Printing an image." << endl;

}

};

Library

WEB DEVELOPMENT

FAANG QUESTIONS