100 likes | 239 Views
CS225: Data Structures and Software Principles Section 4. C++ Inheritance. Outline. Inheritance in C++ Access Permissions Constructors and Initializer Lists Dynamic Binding and Virtual Functions Destructors Abstract Classes. Inheritance Syntax. class Coord { public: Coord();
E N D
CS225: Data Structures and Software PrinciplesSection 4 C++ Inheritance
Outline • Inheritance in C++ • Access Permissions • Constructors and Initializer Lists • Dynamic Binding and Virtual Functions • Destructors • Abstract Classes
Inheritance Syntax class Coord { public: Coord(); Coord(int xInit, int yInit); int getX() const; int getY() const; void print() const; private: int xCoord; // the x-value of our coordinate int yCoord; // the y-value of our coordinate }; Only Coord objects can access xCoord and yCoord directly
Basic Inheritance : Access Permissions LabeledCoord::LabeledCoord() : Coord(), label() { } LabeledCoord::LabeledCoord(int xInit, int yInit, String theLabel) : Coord(xInit, yInit), label(theLabel) { } class LabeledCoord : public Coord { public: LabeledCoord(); LabeledCoord(int xInit, int yInit, String theLabel); String const & getLabel() const; void print() const; private: String label; };
Access Permissions Members Derivation Private Protected Public
Derived Classes • Inherits from parent class • Every data member • Every ordinary member function • Same initial data layout • Doesn’t inherit • Constructors & destructor • Assignment operator • “Friends” • Can add data members, functions, constructors, destructor, friends
Dynamic Binding int main() { Coord c1(4, 5); LabeledCoord l1(3, 9, "Chicago"); c1.print(); l1.print(); Coord* cPtr = new Coord(8, 3); cPtr->print(); delete cPtr; cPtr = new LabeledCoord(7, 4, "Boston"); cPtr->print(); delete cPtr; }
Dynamic Binding class LabeledCoord : public Coord { public: LabeledCoord(); LabeledCoord(int xInit, int yInit, String theLabel); String const & getLabel() const; virtual void print() const; private: String label; };
Virtual Methods • Constructors cannot be virtual • Destructors need to be virtual • Virtual is a keyword that needs to prefix method declaration in header files, not in the .cpp file.
Pure Virtual Methods (Abstract Classes) class Coord { public: Coord(); Coord(int xInit, int yInit); int getX() const; int getY() const; virtual void print() const = 0; // Means you MUST implement in subclasses private: int xCoord; // the x-value of our coordinate int yCoord; // the y-value of our coordinate };