@fernandozamoraj/C++ Inheritance Demo
C++

This C++ demo shows off inheritance from the abstract class FakeObject to Person. It then shows off regular inheritance from Person to Student.

repl talk
Files
  • main.cpp
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
    Author: Fernando Zamora
    Description:  This code shows off examples of inheritance
    It demonstrates how to override base class methods.
    It also demonstrates implementation of an abstract class (FakeObject)


*/
#include <iostream>
#include <string>
using namespace std;


class FakeObject{
  public:
    virtual void SayType() = 0;  //pure virtual... makes this abstract class
};

class Person: public FakeObject{
  
  protected:
  
    string m_name;

  public:
  
    Person();
    virtual void SayName();
    virtual void SayType();
};


Person::Person(){
  m_name = "Joe Smith";  
}

void Person::SayType(){
  std::cout << "My type is Person" << endl;
}
void Person::SayName(){
      std::cout << "I am a person. My Name is " << m_name  << endl;
}

//Student uses Person as its base class
class Student:public Person{
  
  private:
    string m_university;
    
  public:
    void SayName();
    void SayType();
};

void Student::SayName(){
  std::cout << "I am a student. My Name is " << m_name  << endl;
  std::cout << "I attend " << m_university << endl;
}

void Student::SayType(){
  std::cout << "My Type is Student" << endl;
}

int main() {
  
    Person *p1;
    Person *p2;
    
    p1 = new Student;
    p2 = new Person;
    p1->SayName();
    p2->SayName();
    p1->SayType();
    p2->SayType();
}
gcc version 4.6.3