Users Online

· Guests Online: 105

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

Inheritance Program in C++

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

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 1.00 seconds
10,834,385 unique visits