Skip to content

Commit 21a0687

Browse files
committed
Added simpler inheritance example
1 parent 5a2b36b commit 21a0687

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

cpp/cpp1/inheritance.cpp

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#include<iostream>
2+
#include<string>
3+
4+
using namespace std;
5+
6+
class Parent {
7+
protected:
8+
string name;
9+
public:
10+
Parent(const string& n="Person X") : name(n) { cout << " PARENT: constructor for " << name << endl; }
11+
12+
void method1() { cout << " PARENT: method1" << endl; }
13+
void method2() { cout << " PARENT: method2" << endl; }
14+
};
15+
16+
class Child : public Parent {
17+
private:
18+
int age;
19+
public:
20+
Child(const string& n="Baby", const int& a=0) : Parent(n), age(a) { cout << " CHILD: constructor for " <<
21+
name << " age=" << age << endl; }
22+
23+
void method1() { cout << " CHILD: method1" << endl; }
24+
};
25+
26+
int main() {
27+
cout << "Instantiating parent:" << endl;
28+
Parent parentObject("Ward Cleaver");
29+
cout << endl << "Instantiating child:" << endl;
30+
Child childObject("Beaver Cleaver", 8);
31+
32+
cout << endl << "Calling Parent Object methods" << endl;
33+
parentObject.method1();
34+
parentObject.method2();
35+
36+
cout << endl << "Calling Child Object methods" << endl;
37+
childObject.method1();
38+
childObject.method2();
39+
40+
return 0;
41+
}
42+

0 commit comments

Comments
 (0)