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.
Related Posts:
- Practice Computer Science MCQs
- Check Computer Science Books
- Apply for C++ Internship
- Check Programming Books
- Practice Programming MCQs