C++ Program to Illustrate Inheritance

«
»
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. }

advertisement
$ 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
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn