Comp 5421 TA Yanal Alahmad Email yanal tggmail









- Slides: 9

Comp 5421 TA: Yanal Alahmad Email: yanal. tg@gmail. com Date: 31 July, 2019 Reference: [1] C++ How to Program, 10/E Deitel & Deitel

Smart Pointer • Smart pointers are used to make sure that an object is deleted if it is no longer used (referenced)

Smart Pointer void my_func() { int* value. Ptr = new int(15); int x = 45; //. . . if (x == 45) return; // here we have a memory leak, value. Ptr is not deleted //. . . delete value. Ptr; } int main() {}

Smart Pointer #include <memory> void my_func() { std: : unique_ptr<int> value. Ptr(new int(15)); int x = 45; //. . . if (x == 45) return; // no memory leak anymore! //. . . The unique_ptr<> destructor is always called } int main() { }

Multiple Inheritance • Multiple Inheritance is a feature of C++ where a class can inherit from more than one classes. • The constructors of inherited classes are called in the same order in which they are inherited. • The destructors are called in reverse order of constructors. • Run: abc. cpp

Solve Ambiguity class Input. File{ public: void read(); void open(); }; class Output. File{ public: void read(); void open(); }; class IOFile : public Input. File, public Output. File{ }; int main() { IOFile f; f. open(); // this will not work, causes ambiguity which open() to call }

Ambiguity issue class Input. File{ public: void read(); void open(); }; class Output. File{ public: void read(); void open(); }; class IOFile : public Input. File, public Output. File{ }; int main() { IOFile f; f. Output. File: : open(); // solution }

Virtual Inheritance class File { public: string name; void open(); }; class Input. File: public File{ }; class Output. File: public File{ }; class IOFile : public Input. File, public Output. File{ }; int main() { IOFile f; f. open(); // causes ambiguity f. Input. File: : name=“File 1”; // multiple instances f. Output. File: : name=“File 2”; }

Virtual Inheritance class File { public: string name; void open(); }; class Input. File: virtual public File{ }; class Output. File: virtual public File{ }; class IOFile : public Input. File, public Output. File{ }; int main() { IOFile f; f. open(); // will compile // f. Input. File: : name=“File 1”; // no need for them // f. Output. File: : name=“File 2”; }