Lecture 29 - Nov 17, 2023
Today
Inheritance continuation
Recap
What of I want to call a different Person
constructor when I create a Student
object?
class Student : public Person {
private:
int ID;
public:
() { ID = 0; }
Student// or
() : Person(), ID(0) { }
Student
// initializer's list after the :
(string n, int a, int d) : Person(n,a) {
Student= d;
ID }
};
int main() {
("Armaan", 20, 354);
Student s// 1. Person(n,a)
// 2. Student(n,a,d)
}
We have data (private data members) that is inaccesible from the base class.
There is a way to inherit data members and make all of it accessible in the derived class, but mainstain privacy to this data in other classes.
class Person {
protected:
// inherited and accessible
int age;
;
string name};
class Student : public Person {
protected:
int ID;
public:
(string n, int a, int d) {
Student::name = n;
Person::age = a;
Person= d;
ID }
};
("Armaan", 20, 354);
Student s
// s.name will not work
// name is a protected member of Person
// it can't be accessed outside of Person and Student
::: {.callout-note icon=false} ## Example
Multiple inheritances: Insert wheel image with wheel circle radius.
class Circle {
protected:
int radius;
public:
void print() { cout << "Circle" << radius << endl; }
};
class Wheel : public Circle {
// inherits radius and print
protected:
int radius; // another variable with identical name to inherited radius
public:
(int rw) {
Wheel= rw;
radius }
(int rc, int rw) : Circle(rc) {
Wheel= rw;
radius }
void print() {
// radius of circle
::print();
Circle
// radius of wheel
<< "Wheel" << radius << endl;
cout }
}
class Tire : public Wheel {
// inherits radius of wheel, radius of circle, and print of wheel
protected:
int radius;
public:
(int rc, int rw, int rt) : Wheel(rc, rw) {
Tire= rt;
radius }
(int rc, int rw, int rt) : Wheel(rw), Circle(rc) {
Tire= rt;
radius }
void print() {
::print();
Wheel<< "Tire" << radius << endl;
cout }
void set(int rc, int rw, int rt) {
::radius = rc;
Circle::radius = rw;
Wheel= rt;
radius }
};
int main() {
; // 1. Default constructor of Circle
Tire t// 2. Default constructor of Wheel
// 3. Default constructor of Tire is called
// It's provided by the compiler
.set(3,4,6); // circle = 3, wheel = 4, tire = 6
t.print();
t}
Class hierarchy
ADD DIAGRAM
class Person {
// ...
};
class Student : public Person {
// ...
}
class Employee : public Person {
// ...
}
class Grad : public Student {
// ...
}
class TA : public Grad, public Employee {
// ...
}
Pointers to dynamic memory in a derived class
We do not inherit
- Constructors
- Copy constructors
- Operator equal
- Destructors
1: Specify. 2-4: We have to create our own if we need to.