Chapter 13: Introduction to Classes
13.1 Procedural vs Object-Oriented Programming
Procedural: Focuses on functions
Object-Oriented: Focuses on data (objects)
Pros of OOP: Easier to maintain, extend, and protect data using classes.
Terminology
Class: A blueprint for creating objects
Object: An instance of a class
Attributes: Variables inside a class
Methods: Functions inside a class
Public Interface: Accessible part of a class
Data Hiding: Protect internal data using private access
13.2 Creating a Class
Syntax:
class ClassName {
private:
// members
public:
// methods
};
Access Specifiers
public: accessible outside class
private: accessible only within class
Default is private
Member Functions
Declare in class, define using scope resolution operator
Example:
void ClassName::methodName() {}
Accessors and Mutators
Accessor: Gets private data (use const)
Mutator: Sets or modifies private data
Creating and Using Objects
ClassName obj;
obj.setMethod();
cout << obj.getMethod();
Avoiding Stale Data
Always calculate dependent values inside methods instead of storing them
Pointers and Dynamic Allocation
ClassName *ptr = new ClassName;
ptr->method();
delete ptr;
Private Members
Protect internal data; force access via public methods
13.5 Splitting Class Files
Rectangle.h -> class declaration
Rectangle.cpp -> method definitions
#include the header in your main program
Inline Functions
Use for short functions inside class
Pros: Faster execution
Cons: Larger executable
Constructors
Special function with no return type, same name as class
Automatically runs when object is created
Constructor Overloading
Multiple constructors with different parameter lists allowed
Destructors
~ClassName() is automatically called when object is destroyed
Only one allowed per class
Arrays of Objects
ClassName arr[] = { ClassName(args), ... };
Use subscript and dot operator to access