Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
About C++
3.
Feature of C++
4.
Abstract Class in C++
4.1.
Abstract Class in C++ Example
4.1.1.
Output
5.
Pure Virtuality
5.1.
Pure Virtuality Example
5.1.1.
Output
6.
Characteristics of Abstract Classes
7.
Advantages of Abstract Class in C++
8.
Disadvantages of Abstract Class in C++
9.
Importance of Abstraction in Daily Life
10.
Code Implementation
10.1.
Output
11.
Frequently Asked Questions
11.1.
What is abstract class in CPP?
11.2.
Does CPP have abstract class?
11.3.
How do I create an abstract class in CPP?
12.
Conclusion
Last Updated: Mar 27, 2024
Easy

Get to know Abstract Class in C++

Author Lekhika
1 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Hello Ninjas, as you may know, C++ is one of the most used programming languages because its syntax is simple, direct, straightforward, and elegant, allowing code to be written in fewer lines than other programming languages. 

C++ Abstract Class

In this article, we will cover the topic of Cpp Abstract Class. Before diving deep into the topic, let us know something about C++. Also see, Literals in C.Fibonacci Series in C++

About C++

C++ is a general-purpose programming language created by Bjarne Stroustrup at Bell Labs in the early 1980s. C++ is quite similar to C, and it is compatible with C that it can run 99 percent of C programs without changing any source code.

C++

However, because C++ is an object-oriented programming language, it is a safer and more well-structured programming language than C.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Feature of C++

Following are some C++ procedural and object-oriented features.

💢Bottom-Up approach.

💢Supports function overloading.

💢Operator overloading is possible.

💢It is divided into functions and classes.

💢cin and cout are mainly used for input/output.

💢Try and catch is used for exception handling.

💢Reference variables are supported in C++.

💢Functions can be used in a structure.

💢Virtual and friendly functions are supported.

💢Structures support access modifiers in C++.

Abstract Class in C++

In Daily Life, Abstraction Is Important.

Abstraction basically means to show only the specific data and hide the details of a particular data.

The ATM serves as another real-world illustration of abstraction. However, we all use it to accomplish financial transactions like cash withdrawals, money transfers, and retrieving mini-statements. We have no permit for the ATM's internal data. Data can be shielded from illegal access by using data abstraction.

A class that contains at least one pure virtual function. We can't declare the object of an abstract class.

Syntax: 

class A{
Public:
	Virtual void show()=0;
};

 

In C++, a class with at least one Pure Virtual function is stated to be an abstract class. To offer multiple inheritances for its child classes, abstract classes are employed. Classes that inherit from Abstract Classes must define the pure virtual function to avoid becoming Abstract Classes.

Abstract Class in C++ Example

#include <iostream>

// Abstract class
class Shape {
public:
    // Pure virtual function
    virtual double area() = 0;
    virtual void display() = 0;
};

// Concrete class Circle derived from Shape
class Circle : public Shape {
private:
    double radius;

public:
    Circle(double r) : radius(r) {}

    double area() override {
        return 3.14 * radius * radius;
    }

    void display() override {
        std::cout << "This is a circle." << std::endl;
    }
};

// Concrete class Rectangle derived from Shape
class Rectangle : public Shape {
private:
    double length;
    double width;

public:
    Rectangle(double l, double w) : length(l), width(w) {}

    double area() override {
        return length * width;
    }

    void display() override {
        std::cout << "This is a rectangle." << std::endl;
    }
};

int main() {
    Circle circle(5);
    Rectangle rectangle(4, 6);

    Shape* shape1 = &circle;
    Shape* shape2 = &rectangle;

    shape1->display();
    std::cout << "Area: " << shape1->area() << std::endl;

    shape2->display();
    std::cout << "Area: " << shape2->area() << std::endl;

    return 0;
}

Output

This is a circle.
Area: 78.5
This is a rectangle.
Area: 24

Pure Virtuality

It is possible to quickly describe pure virtual functions in the Abstract class, which shares all derived classes. The ability to create objects of the Abstract class still needs to be made available.

Additionally, the class description and the Pure Virtual function must be given individually. If defined in the class description, the compiler will throw an error. The pure virtual inline definition is invalid.

Pure Virtuality Example

#include <iostream>
using namespace std;


// This is the Abstract class below.
class ThisisBaseClass {
   public:
    
    // This is a pure virtual Function below.
    virtual void display() = 0;
};


// This is Derived class below.
class ThisisDerivedClass : public ThisisBaseClass {
   public:
    void display() {
        cout << "Abstract class and pure virtual function implementation.";
    }
};


int main() {
    ThisisDerivedClass obj;
    obj.display();
    return 0;
}

Output

Output

 

You practice by yourself with the help of online c++ compiler.

Characteristics of Abstract Classes

Although abstract class objects cannot be constructed, they can be represented by pointers and references. Besides pure virtual functions, abstract classes can also have regular functions and variables. All pure virtual functions must be implemented for a class to inherit from an abstract class to avoid becoming abstract themselves.

The following are some characteristics.

Characteristics of Abstract Classes


Note: Why can't we make a CPP abstract class object?

We cannot create an abstract class object because there is an abstract method with no parameters, which you can also call. If we create an abstract class object and call a method with no body (because the method is purely virtual), we will get an error.

Advantages of Abstract Class in C++

The following are some advantages of an abstract class:

Advantages of CPP Abstract Class

🍁The internal class's execution can be changed without impacting the user.

🍁It improves an application's or program's privacy by only displaying appropriate information to the user.

🍁It prevents the user from writing low-level code.

🍁It reduces program duplication and increases program reusability.

🍁The class implementation may change over time in response to new requirements or problem reports without requiring changes to user-level code.

Disadvantages of Abstract Class in C++

The following are some disadvantages of an abstract class:

🍁 Abstract classes add complexity.

🍁 Suppose we make the constructor of an abstract class that calls a pure virtual function. In Java, this works because the subclass implements the abstract method that is called. In C++, it shows an error.

Importance of Abstraction in Daily Life

Abstraction is required for computational thinking and problem-solving. Following are some places where we use abstraction on a daily basis-

⭐ Baking a cake.

⭐ Using available colors and outfit combinations to dress in the morning.

⭐ Driving to work.

⭐ Listening to music using headphones.

⭐ Taking a picture on a smartphone.

The above examples use abstraction to hide detailed information, like driving to work without knowing the mechanism of the engine and other parts. We listen to music using headphones but didn't see the signal transmission, etc.

Code Implementation

// Implementation of CPP abstract class.
#include<iostream>
using namespace std;
class familyLastName 
{
   public:
      virtual void Surname() = 0 ;
};
class familyBoyFName: public familyLastName 
{
   public:
   void boyfname(string name)
   {
       cout<<name<<" ";
   }
      void Surname() 
      {
         cout<< "Sharma\n";
      }
};
class familyGirlFName: public familyLastName 
{
   public:
   void girlname(string name)
   {
       cout<<name <<" ";
    }
   void Surname() 
   {
         cout<< "Sharma\n";
     }
};
int main()
{
   string bName, gName;
   	cout<<"Enter Boy's name: ";
   	cin>>bName;
   	 
   familyBoyFName boy;
   	boy.boyfname(bName);
  	boy.Surname();
   	cout<<"Enter Girl's name: ";
   	cin>>gName;
   familyGirlFName girl;
   	girl.girlname(gName);
   	girl.Surname();
	return 0;
}

Output

output

 

Must Read Dynamic Binding in C++

Frequently Asked Questions

What is abstract class in CPP?

In C++, an abstract class is a class that cannot be instantiated and serves as a blueprint for derived classes. It may contain pure virtual functions, making it a key component of polymorphism and inheritance.

Does CPP have abstract class?

Yes, C++ supports abstract classes. 

How do I create an abstract class in CPP?

To create an abstract class in C++:

  1. Use the class keyword.
  2. Include at least one pure virtual function (declared with "= 0").
  3. Derive concrete classes from it.

Conclusion

We have covered c++, its features, abstract class, its characteristics, importance, code, etc., in this article. We hope this article helps you enhance your knowledge of the CPP Abstract Class.

We encourage you to check out our other articles to learn more about C++.


To study more about data types, refer to Abstract Data Types in C++ and Data Types in C++.

We hope you have gained a better understanding of these topics now! Are you planning to ace the interviews with reputed product-based companies like AmazonGoogleMicrosoft, and more? 

Attempt our Online Mock Test Series on Coding Ninjas Studio now!

Previous article
Parameterized Constructors in C++
Next article
Function Overloading and Overriding in C++
Live masterclass