📚

C++ Class Methods Overview

Sep 8, 2024

C++ Programming Language Lecture Notes

Overview

  • The lecture continues the series on learning C++ programming.
  • Recap of previous topics: Access Specifiers (private, public, protected) - protected will be discussed later in the course.
  • Focus of this video: Implementing class methods (member functions).

Class Methods

  • Definition: Class methods are functions associated with a specific class (member functions).
  • Three ways to implement class methods:
    1. Inside the class
    2. Outside the class
    3. Separate declaration and definition

1. Implementing Inside the Class

  • Methods can be defined directly inside the class, typically for short functions (inline functions).
  • Example: Getter and Setter methods for private attributes (e.g., name, balance).

2. Implementing Outside the Class

  • Methods can also be defined outside the class, while still being part of the same file.
  • Syntax for defining outside:
    • Use the return type, class name, scope resolution operator, and function name.
    • Example: Implementing deposit and withdraw methods.

3. Separate Declaration and Definition

  • Generally for larger projects, separate declarations and definitions into different files:
    • Header file (.h): Contains class declaration and method signatures.
    • Source file (.cpp): Contains the implementation of the methods.
  • Recommended for better organization in large projects.

Header File Structure

  • Use include guards to prevent multiple inclusions: #ifndef HEADER_NAME_H #define HEADER_NAME_H // Class definitions #endif

Example Implementation Steps

  1. Create header file (e.g., Implement3.h):
    • Only class declaration without method definitions.
  2. Create source file (e.g., Implement3.cpp):
    • Include the header file and define the methods.
  3. Create main file (e.g., main_Implement3.cpp):
    • Create objects and call methods from the class.

Compilation

  • Compile multiple files together using g++: g++ main_Implement3.cpp Implement3.cpp
  • Ensure all files are properly linked to avoid "undefined reference" errors.

Conclusion

  • The lecture emphasized the three methods of implementing class methods and the importance of separating specifications from implementations in larger projects.
  • Encourage practice in organizing projects with header and source files.
  • Request for engagement: Likes target of 500 for motivation.