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.
/*
* C++ Program to Illustrate Inheritance
*/
#include <iostream>
class Base {
protected:
int data;
public:
Base(int val = 0) : data(val) { }
int getData(void) const { return data; }
};
class Derived : public Base {
public:
void changeData(int val)
{
std::cout << "Change of Derived::data from "
<< data << "->" << val << std::endl;
data = val;
}
};
int main()
{
Base b;
Derived d;
d.changeData(20);
// getData is available to Derived Class
std::cout << "Base Class data = " << b.getData() << std::endl;
std::cout << "Derived Class data = " << d.getData() << std::endl;
}
$ 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.
Next Steps:
- Get Free Certificate of Merit in C++ Programming
- Participate in C++ Programming Certification Contest
- Become a Top Ranker in C++ Programming
- Take C++ Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Apply for Information Technology Internship
- Buy Computer Science Books
- Buy Programming Books
- Apply for Computer Science Internship
- Practice Programming MCQs