From 7b9c74b098ea6257fb031b1cb6adcfe29a1f7be3 Mon Sep 17 00:00:00 2001 From: Jidong Xiao Date: Fri, 11 Apr 2025 04:41:44 -0400 Subject: [PATCH] adding exercise 1 --- lectures/25_inheritance/README.md | 37 +++++++++++++++++++ .../25_inheritance/exercises/exercise1.cpp | 31 ++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 lectures/25_inheritance/exercises/exercise1.cpp diff --git a/lectures/25_inheritance/README.md b/lectures/25_inheritance/README.md index 316a12b..250c141 100644 --- a/lectures/25_inheritance/README.md +++ b/lectures/25_inheritance/README.md @@ -172,3 +172,40 @@ We develop this student_test.cpp program. ### version 3 [student_test3.cpp](student_test3.cpp) In this version, the child class has its own member functions introduce() and sleep(); and because these functions need to access the parent class's member variables, so we changed the member variables from private to protected. + +### version 4 + +[student_test4.cpp](student_test4.cpp) In this version, we added the destructor to both the child class and the parent class. This program shows that when the child class object is destroyed, first its own destructor gets called, and then its parent destructor gets called. + +## 25.7 What will be printed when running this program? + +#include + +class A { +public: + A() { + std::cout << "A"; + } + ~A() { + std::cout << "A"; + } +}; + +class B : public A { +public: + B() { + std::cout << "B"; + } + ~B() { + std::cout << "B"; + } +}; + +int main() { + { + A a; + B b; + } + std::cout << std::endl; + return 0; +} diff --git a/lectures/25_inheritance/exercises/exercise1.cpp b/lectures/25_inheritance/exercises/exercise1.cpp new file mode 100644 index 0000000..265e975 --- /dev/null +++ b/lectures/25_inheritance/exercises/exercise1.cpp @@ -0,0 +1,31 @@ +#include + +class A { +public: + A() { + std::cout << "A"; + } + ~A() { + std::cout << "A"; + } +}; + +class B : public A { +public: + B() { + std::cout << "B"; + } + ~B() { + std::cout << "B"; + } +}; + +int main() { + { + A a; + B b; + } + std::cout << std::endl; + return 0; +} +