Advanced C++ Concepts

Jul 29, 2024

C++ Advanced Concepts

Lecture Overview

  • Continuation of Part 1
  • Focus on advanced C++ topics: pointers, object-oriented programming (OOP), structures, classes, method overloading, overriding, and virtual methods.

Pointers

  • Definition: Pointers store memory addresses of variables.
  • Syntax: int* ptr = &var; // ptr stores the address of var
  • Printing Pointers:
    • To print value: std::cout << *ptr;
    • To print address: std::cout << ptr;
  • Memory Sizes:
    • int - 4 bytes
    • float - 4 bytes
    • double - 8 bytes
    • char - 1 byte
    • Pointers can also point to arrays, functions, etc.
  • Array and Pointers:
    • Arrays are pointers to their first element.
    • Example: int arr[5] = {1, 2, 3, 4, 5}; int* ptr = arr;

Functions and Pointers

  • Passing Pointers to functions to modify the original variable.
  • Passing by reference vs. Passing by value:
    • void func(int& a) vs. void func(int a)

Structures

  • Syntax:
    struct Car {
      int wheels;
      std::string brand;
      std::string color;
      int maxSpeed;
      void printProperties();
    };
    
  • Creating an instance: Car myCar;
  • Accessing members: myCar.wheels = 4;

Classes

  • Similar to structs but with access specifiers:
    • private for private members (not accessible outside class)
    • public for public members
  • Class Constructor and Destructor:
    • Constructor: MyClass() { /*...*/ }
    • Destructor: ~MyClass() { /*...*/ }

Inheritance

  • Deriving Classes:
    • Example:
    class Car : public Vehicle {
      std::string model;
      // Additional members and methods
    };
    

Encapsulation

  • Private and Public Members:
    • Use private for sensitive data.
    • Use getters and setters for accessing private members.

Method Overloading

  • Overloading: Same function name, different parameters.
    • Example:
    void func();
    void func(int a);
    void func(int a, float b);
    

Method Overriding

  • Overriding: Redefining a superclass method in a subclass.
    • Use virtual keyword.
    • Example:
    class Vehicle {
      virtual void getClassType() { std::cout << "Vehicle"; }
    };
    class Car : public Vehicle {
      void getClassType() override { std::cout << "Car"; }
    };
    

Virtual Methods

  • Definition: Methods that can be overridden in derived classes.
  • Syntax: virtual void myMethod();
  • Usage: Polymorphism in OOP.

Conclusion

  • Recap of advanced C++ topics discussed.
  • Open for emails or comments for questions and suggestions.
  • Happy New Year!