Posts

Showing posts from February, 2020

Templates

Just as a function  parameterizes  values, templates parameterize  types . Types include primitives such as  int  as well as user-defined classes. Class Templates Class templates define a class where some types, return types of methods or parameters to those methods are specified as parameters for client code to instantiate. Class templates are suited for container objects. The following discussion uses the  Grid  class shown in  Professional C++ . All the following examples are from  Professional C++  as well. Defining a class template A generic game board can be envisioned which stores chess pieces, checkers pieces, tic-tac-toe pieces or any other 2D game board pieces. Without templates, the approach to take would be polymorphism.  GamePiece  is the base class and  ChessPiece  would derive from it. To copy a  GameBoard , one has to be able to copy  GamePiece s. A pure virtual  clone  method could be used: class GamePiece { public : virtual std :: unique_pt

Inheritance

Image
Inheritance One can extend a parent class with additional behavior. Then the class automatically contains the data members and methods of the original  parent  or  base  class. Here is the syntax: class Base { public : void fooMethod ( ) ; protected : string mProtectedString ; private : double mPrivateDouble ; } To derive from this base class: class Derived : public Base { public : void aNewMethod ( ) ; } Additional classes can inherit from  Base  and they would be siblings of  Derived . The  Base  class has no idea about the  Derived  class. A pointer or reference to  Base  could actually be pointing at a  Derived . For example, the following code is valid: Base * b = new Derived ( ) ; However, one cannot call methods in derived on  b . Derived class has access to  public  and  protected  members of the base class. To prevent inheritance, one can mark a class as  final . In order to override methods o