Oops - C P P

Basic


  • Programming Technique
    • Object-oriented Programming
      • Classes, Objects
      • 4 pillars => Inheritance, Polymorphism, Encapsulation, Abstraction
  • Static
    • Common for all Objects of that Class, Belongs to Class instead of Object
      • Can be accessed without creating a Object
    • static dataType variable; => Declare a static variable
    • dataType ClassName::variable = value; => Initialize
    • ClassName::variable => Called using Class instead of Object
      • Can also be accessed with Object but not recommended
    • Static methods can only access Static data member
    • this can't be used in Static method
  • Constant Methods
    • Can't modify value
    • Can be invoked by both const and non-const Objects
  • Structure Member Alignment
    • Alignment of data/bytes sequently (multiple of 2/4/8) in memory so that CPU requires least number of read cycles to fetch the data
  • Padding
    • Extra memory (Padding) is required so that the next memory allocation in in multiple of 2/4/8/...
    • The programmer should declare the structure members in their increasing/decreasing order of size
  • Data Packing
    • Some times it is mandatory to avoid padded bytes among the members of structure

Class


  • It is a blueprint => Design/Type
    • State/Property/Field/Data Member/Attributes
    • Behavior/Function/Data Function/Methods
  • Class can be created in another file and imported
    • #include "ClassName.cpp"
  • Everything in the Class is private by default
  • Creating a Class
        class ClassName {
            // Properties
            // Methods
        };
    

Object


  • Implementation/Instance of Class
    • Occupies 1 byte in case on empty class for tracking
  • this => Represents address of current Object
    • this->variable => Access Property of Class
  • Commands
    • Initialize a Object of a Class
          // Static Allocation
          ClassName variable;
      
          // Dynamic Allocation
          ClassName *variable = new ClassName;
          ClassName *variable = new ClassName();
      
    • Access Properties & Methods of that class
          // For Static Allocation
          var.variableName = value;
          var.functionName();
      
          // For Dynamic Allocation
          (*var).variableName;
          var->variableName;
          (*var).functionName();
          var->functionName();
      
    • Pointer will point to NULL
          ClassName variable1;
          ClassName *ptr = &variable1;
          ptr = NULL;
      
    • Constant Methods
          // Cannot be modified, Can invoke only const member functions
          // Needs to be initialized at the time of declaration via constructors
          const ClassName variable;
      

Constructor


  • Gets called during Object creation
    • Same name as Class name
    • Does not have a return data type
    • Can't use abstract/static/final/synchronized with Constructor
  • Inbuilt constructor
    • Default constructor & Copy constructor & Destructor is created by compiler automatically when Class is created
    • Default constructor is removed if any user defined constructor (even parameterized) exits
  • Types
    • Default/No Argument
          // Gets called when creating an Object with giving parameter
          ClassName () {
              variable = value;
          }
          // Calling It
          ClassName variable;
      
    • Parameterized
          ClassName (dataType value) {
              this->var = value;
          }
          // Calling It, Default Constructor should exit
          ClassName variable(argument);
      
    • Copy
      • Shallow copy
        • Same memory with different names
        • Any changes made will be reflected in both
      • Deep Copy
        • Copies all fields and makes copies of dynamically allocated memory pointed to by the fields
      • Creating
            // Default Copy constructor does Shallow copy
            // If passed by value then loop of Copy constructor will be created
            ClassName (ClassName &var) {
                this->variable1 = var.variable1;
                this->variable2 = var.variable2;
            }
            // Calling It
            ClassName variable(objectName);
            ClassName variable = objectName;
        
      • variable1 = variable2 => Values of variable2 are copied in variable1 Object
  • Destructor
    • Used to de-allocate memory
    • Gets called when variables are going out of scope
      • Automatically gets called for static allocation but not for dynamic allocation
      • delete variable; => Calling for dynamic allocation
    • Creating
          ~ClassName() {
              // Statement
          }
      
  • Initializer List
    • Used in initializing the data members of a class using constructors
    • Creating
          int x;
          int y;
          
          ClassName(int variable1 = 0, int variable2 = 0):x(variable1), y(variable2) {}
          // Same As
          ClassName(int variable1 = 0, int variable2 = 0) {
              x = variable1;
              y = variable2;
          }
      
    • For initialization of non-static const data members this is must
      • No memory is allocated separately for const data member, it is folded in the symbol table
      • Creating
            const int variable;
            ClassName(int variable):variable(variable) {}
        
    • For initialization of reference members
          int &variable;
          ClassName(int &variable):variable(variable) {}
      
    • For initialization of member objects which do not have default constructor
    • For initialization of base class members
    • When constructor’s parameter name is same as data member, this can also be used
  • Private Constructor
    • To control how the class is instantiated
  • Constructor Chaining/Delegating Constructor
  • Constructor Overloading
    • Having same name but different parameters, Can be applied with parameterized constructors

Inheritance


  • Inherits property of a Class (Parent/Super) to another Class (Child/Sub)
    • Allows reusability
  • super => Used to access methods of Parent/Base class from children class
  • Inheritance Table
  • Types
    • Single
          // B inherits A
          class ClassNameB: accessModifier ClassNameA {
              // Statements
          };
      
    • Multi-level
          // B inherits A & C inherits B
          class ClassNameB: accessModifier ClassNameA {
              // Statements
          };
          class ClassNameC: accessModifier ClassNameB {
              // Statements
          };
      
    • Hierarchical
          // B & C inherits A
          class ClassNameB: accessModifier ClassNameA {
              // Statements
          };
          class ClassNameC: accessModifier ClassNameA {
              // Statements
          };
      
    • Multiple
          // C inherits A & B
          class ClassNameC: accessModifier ClassNameA, accessModifier ClassNameB {
              // Statements
          };
      
    • Hybrid/Multi-path
      • Combination of more than 1 type of inheritance
  • :: => Scope resolution operator
    • To remove ambiguity of Multiple inheritance
    • A & B have method with same name
      • variable.A::functionName(); => Function of Class A gets called

Polymorphism


  • Same Objects acting in many forms
    • Depending on Overloaded/Overridden methods
  • Types
    • Compile-time/Static Polymorphism/Early Binding
      • Function Overloading
        • Same function with different functionalities based on different Parameters (Number or dataType)
        • returnType can also be changed but it will not cause Overloading
      • Operator Overloading
        • Operators Allowed
        • Unary
              returnType operator++() {
                  // Statements
              }
          
        • Binary
              // 1st argument is by Object, 2nd argument is passed
              returnType operator+(ClassName &var) {
                  // Statements
              }
              variable1 + variable2;
          
    • Run-time/Dynamic Polymorphism/Late Binding
      • Function Overriding
        • Same function with different functionalities in different Classes
        • Name & Parameter should be same of functions, Works only through Inheritance
        • We cannot override static methods
        • Virtual Function
          • They are always defined in the base class and overridden in a derived class
          • Can't be static, can be a friend function of another class
          • Should be accessed using pointer or reference of base class type to achieve runtime polymorphism
          • Late binding (Runtime) is done in accordance with the content of pointer (i.e. location pointed to by pointer) and Early binding (Compile time) is done according to the type of pointer
          • Creating
                // Base Class
                virtual void print() {}
                void show() {}
                
                // Derived Class: Base Class
                void print() {}
                void show() {}
                
                // Main
                Base *ptr;
                Derived var;
                ptr = &var;
            
                // Virtual function, binded at runtime
                ptr->print();
                // Non-virtual function, binded at compile time
                ptr->show();
            
          • Pure Virtual Function (Abstract Function)
            • Have implementation, But we must override that function in the derived class
            • Creating
                  class ClassName {
                      public:
                      virtual returnType functionName() = 0;
                  }
              
          • Virtual Destructor
            • Deleting a derived class object using a pointer of base class type that has a non-virtual destructor results in undefined behavior, Destructor of derived class is not called
            • All destructor called
                  // Base Class
                  virtual ~ClassName1() {}
                  // Derived Class
                  virtual ~ClassName2() {}
                  // Main
                  Derived *d = new Derived(); 
                  Base *b = d;
                  delete b;
              

Encapsulation


  • Wrapping up data member and function
    • Information hiding, More security
    • Without setter, Class can be made read only
    • Benefits in Unit testing
  • Fully encapsulated class
    • All data members are private
  • Getters => Used to get a private variable
    • Creating a Getter Function
          returnType getVarName () {
              return var;
          }
      
  • Setters => Used to set a private variable
    • Creating a Setter Function
          void setVarName (dataType val) {
              this.var = val;
          }
      
  • Access Modifiers => Used for Data Hiding for Properties & Methods
    • private
      • By default
      • Accessible only within the Class
      • private:
    • public
      • Accessible to everyone
      • public:
    • protected
      • Accessible within Class and in child Class
      • protected:
  • Friend Class
    • Can access private and protected members of other class in which it is declared as friend
    • friend class ClassName;
  • Friend Function
    • Can access private and protected members of other class in which it is declared as friend
    • friend returnType functionName();
    • This function can be a member of another class or a global function

Abstraction


  • Showing only essential details
    • Implementation hiding
    • Reduces complexity of viewing things
  • Interfaces
    • Behavior or capabilities of a class without committing to a particular implementation of that class
  • Abstract Class
    • A class is abstract if it has at least one pure virtual function
    • Cannot be used to instantiate objects and serves only as an interface
    • No object of abstract class possible
    • Pure Abstraction => All methods are without implementation
    • Pointers and references of abstract class
          class ClassName1 {
              public:
              virtual returnType functionName() = 0;
          }
          class ClassName2: public CLassName1 {
              public:
              returnType functionName() {
                  // Statements
              };
          }
          // Main
          ClassName1 *ptr = new ClassName2();
          ptr->show();
      
    • If we do not override the pure virtual function in derived class, then derived class also becomes abstract class
Share: