Professional Documents
Culture Documents
Advantage of C++ Inheritance
Advantage of C++ Inheritance
In C++, inheritance is a process in which one object acquires all the properties and
behaviors of its parent object automatically. In such way, you can reuse, extend or modify
the attributes and behaviors which are defined in other class.
In C++, the class which inherits the members of another class is called derived class and
the class whose members are inherited is called base class. The derived class is the
specialized class for the base class.
1. #include <iostream>
2. using namespace std;
3. class Account {
4. public:
5. float salary = 60000;
6. };
7. class Programmer: public Account
8. {
9. public:
10. float bonus = 5000;
11. };
12. int main(void)
13. {
14. Programmer p1;
15. cout<<"Salary: "<<p1.salary<<endl;
16. cout<<"Bonus: "<<p1.bonus<<endl;
17. return 0;
18. }
Output:
Salary: 60000
Bonus: 5000
1. #include <iostream>
2. using namespace std;
3. class Animal {
4. public:
5. void eat() {
6. cout<<"Eating..."<<endl;
7. }
8. };
9. class Dog: public Animal
10. {
11. public:
12. void bark(){
13. cout<<"Barking...";
14. }
15. };
16. int main(void) {
17. Dog d1;
18. d1.eat();
19. d1.bark();
20. return 0;
21. }
Output:
Eating...
Barking...
1. #include <iostream>
2. using namespace std;
3. class Animal {
4. public:
5. void eat() {
6. cout<<"Eating..."<<endl;
7. }
8. };
9. class Dog: public Animal
10. {
11. public:
12. void bark(){
13. cout<<"Barking..."<<endl;
14. }
15. };
16. class BabyDog: public Dog
17. {
18. public:
19. void weep() {
20. cout<<"Weeping...";
21. }
22. };
23. int main(void) {
24. BabyDog d1;
25. d1.eat();
26. d1.bark();
27. d1.weep();
28. return 0;
29. }
1. #include <iostream>
2. using namespace std;
3. class Address {
4. public:
5. string addressLine, city, state;
6. Address(string addressLine, string city, string state)
7. {
8. this->addressLine = addressLine;
9. this->city = city;
10. this->state = state;
11. }
12. };
13. class Employee
14. {
15. private:
16. Address* address; //Employee HAS-A Address
17. public:
18. int id;
19. string name;
20. Employee(int id, string name, Address* address)
21. {
22. this->id = id;
23. this->name = name;
24. this->address = address;
25. }
26. void display()
27. {
28. cout<<id <<" "<<name<< " "<<
29. address->addressLine<< " "<< address->city<< " "<<address->state<<endl;
30. }
31. };
32. int main(void) {
33. Address a1= Address("C-146, Sec-15","Noida","UP");
34. Employee e1 = Employee(101,"Nakul",&a1);
35. e1.display();
36. return 0;
37. }