Lecture 26 - Nov 14, 2023
Summary
In this lecture, we continue our discussion on complexity analysis, and how we get evaluate the big-O of recursive functions.
Last lecture
Complexity analysis.
Today
Inheritance.
Inheritance
Inheritance is a pillar of object-oriented programming.
Inheriting/acquiring all properties and behaviours of a parent class.
In Person.h
:
class Person {
private:
;
string nameint age;
public:
() { name = ""; age = 0; }
Person(string n, int a) { name = n; age = a; }
Personvoid setName(string n) { name = n; }
void print() {
<< "Name: " << name << endl;
cout << "Age: " << age << endl;
cout }
};
I want to create a class Student
. The data for this class should be: name, age, and ID. The functions should be: setName()
, print()
, and setNameID()
.
I can reuse some of the code.
Option 1: From scratch.
Option 2: Copy and paste code from Person
class and add setNameID()
. The issues are:
- Understand all details of
Person
. - If you change
Person
, no changes will be reflected toStudent
.
Option 3: Inherit from Person
. The benefits are:
- Re-use code.
- Need to understand what
Person
does.
Person
is a base class.
Student
is a derived class.
In Student.h
:
class Student : public Person {
private:
int ID;
// age and name are innaccessible
// we don't inherit constructors of Person
public:
() : Person() { ID = 0; }
Student
// setName is inherited
void setNameID(string n, int d) {
::setName(n);
Person= d;
ID }
// method overriding: replace/redefine the inherited print() from Person
// we define our own version for Student
void print() {
<< "ID: " << ID << endl;
cout
// I can't access age and name
::print();
Person}
};
In main.cpp
:
#include "Person.h"
#include "Student.h"
using namespace std;
int main() {
("Joe", 23);
Person p
// name and age are inaccessible
;
Student s
// 1. we construct Person object
// 2. On top of it, we construct Student object
// setName is inherited from Person, so we can call it on Student
.setName("Ryan");
s
.setNameID("Marina", 125);
s}