Abstract Class Program in C++

This C++ program illustrates abstract classes. Abstract classes are used to represent general concepts, which can be used as base classes for concrete classes. An abstract class is one which has atleast one purely virtual function. We can not create instance of such class. The program creates a derived class whose instance is created and is manipulated.

Here is the source code of the C++ program which illustrates abstract classes. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Illustrate Abstract Class
  3.  */
  4. #include <iostream>
  5. using namespace std;
  6.  
  7. class Abstract {
  8.     int i, j;
  9.     public:
  10.         virtual void setData(int i = 0, int j = 0) = 0;
  11.         virtual void printData() = 0;
  12. };
  13.  
  14. class Derived : public Abstract {
  15.     int i, j;
  16.     public:
  17.         Derived(int ii = 0, int jj = 0) : i(ii), j(jj)
  18.         {
  19.             cout << "Creating object " << endl;
  20.         }
  21.         void setData(int ii = 0, int jj = 0)
  22.         {
  23.             i = ii;
  24.             j = jj;
  25.         }
  26.         void printData()
  27.         {
  28.             cout << "Derived::i = " << i << endl
  29.                  << "Derived::j = " << j << endl;
  30.         }
  31. };
  32.  
  33. int main()
  34. {
  35.     // Cannot create an instance of Abstract Class
  36.     // Abstract a;
  37.     Derived d;
  38.  
  39.     cout << "Current data " << endl;
  40.     d.printData();
  41.     d.setData(10, 20);
  42.     cout << "New data " << endl;
  43.     d.printData();
  44. }

$ a.out
Creating object 
Current data 
Derived::i = 0
Derived::j = 0
New data 
Derived::i = 10
Derived::j = 20

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.