Inheritance Program in C++

This C++ program illustrates inheritance. Inheritance allows us to define a class in terms of another class. This also provides an opportunity to reuse the code functionality and fast implementation time. The data member and member functions defined in the base class are available in the derived class.

Here is the source code of the C++ program illustrates inheritance. 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 Inheritance
  3.  */
  4. #include <iostream>
  5.  
  6. class Base {
  7.     protected:
  8.         int data;
  9.     public:
  10.         Base(int val = 0) : data(val) { }
  11.         int getData(void) const { return data; }
  12. };
  13.  
  14. class Derived : public Base {
  15.     public:
  16.         void changeData(int val)
  17.         {
  18.             std::cout << "Change of Derived::data from "
  19.                       << data << "->" << val << std::endl;
  20.             data = val; 
  21.         }
  22. };
  23.  
  24.  
  25. int main()
  26. {
  27.     Base b;
  28.     Derived d;
  29.  
  30.     d.changeData(20);
  31.     // getData is available to Derived Class
  32.     std::cout << "Base Class data = " << b.getData() << std::endl;
  33.     std::cout << "Derived Class data = " << d.getData() << std::endl;
  34. }

$ a.out
Change of Derived::data from 0->20
Base Class data = 0
Derived Class data = 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.

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.