C++ Classes & Objects
Modern C++ Classes and Objects
Section titled “Modern C++ Classes and Objects”Object-Oriented Programming (OOP) is a cornerstone of C++, and classes are the fundamental building block for creating your own custom types that model real-world or abstract concepts.
Think of a class as a blueprint for creating objects. It defines a structure containing both data (called member variables or attributes) and operations that can be performed on that data (called member functions or methods). An object is a specific instance created from that class blueprint.
C++ Class Definitions
Section titled “C++ Class Definitions”Defining a class creates a new data type. It doesn’t create any objects yet, but it specifies what objects of this type will look like and what they can do.
A class definition starts with the class keyword, followed by the class name, and then the class body enclosed in curly braces {}. The definition must end with a semicolon ;. Inside the body, we declare members (variables and functions).
class Box {public: // Constructor (Optional but recommended for initialization) Box(double l = 1.0, double b = 1.0, double h = 1.0) : length{l}, breadth{b}, height{h} // Modern initializer list {}
// Member function to calculate volume double getVolume() const { // 'const' indicates this function doesn't modify the object return length * breadth * height; }
// Member function to set dimensions void setDimensions(double l, double b, double h) { length = l; breadth = b; height = h; }
// Public member variables (Generally prefer private members and public methods) double length; double breadth; double height;
// private: // Member variables are often private for encapsulation // double length; // double breadth; // double height;}; // Don't forget the semicolon!Access Specifiers: public, private, protected
Section titled “Access Specifiers: public, private, protected”Access specifiers control how members of a class can be accessed:
public: Members declared as public can be accessed from anywhere outside the class, as long as you have an object of that class.private: Members declared as private can only be accessed by member functions and friend functions of the class itself. This is the default access level if none is specified. Encapsulation is typically achieved by making data members private and providing public member functions (getters/setters) to control access.protected: Similar to private, but protected members can also be accessed by member functions and friends of derived classes (used in inheritance).
Creating and Using C++ Objects
Section titled “Creating and Using C++ Objects”Once a class is defined, you can create objects (instances) of that class, much like declaring variables of built-in types:
#include <iostream>
// Assume Box class definition from above is here or included
int main() { Box smallBox; // Create a Box object using the default constructor (1.0, 1.0, 1.0) Box largeBox{10.0, 12.0, 13.0}; // Create using constructor with values (C++11 uniform initialization) Box mediumBox(5.0, 6.0, 7.0); // Alternative constructor call syntax
// Access public members using the dot operator (.) // mediumBox.length = 5.0; // Direct access if public (as in example) // mediumBox.breadth = 6.0; // mediumBox.height = 7.0;
// Call public member functions double smallVolume = smallBox.getVolume(); std::cout << "Volume of smallBox: " << smallVolume << std::endl;
double mediumVolume = mediumBox.getVolume(); std::cout << "Volume of mediumBox: " << mediumVolume << std::endl;
largeBox.setDimensions(11.0, 13.0, 14.0); // Modify using a member function std::cout << "Volume of largeBox after setDimensions: " << largeBox.getVolume() << std::endl;
// Accessing private members directly would cause a compile-time error: // std::cout << mediumBox.height; // Error if height were private
return 0;}When the above code is compiled and executed, it produces:
Volume of smallBox: 1Volume of mediumBox: 210Volume of largeBox after setDimensions: 2002Key Concepts Related to Classes & Objects
Section titled “Key Concepts Related to Classes & Objects”Here’s a breakdown of essential concepts related to C++ classes and objects:
| Concept | Description |
|---|---|
| Member Functions | Functions defined within a class scope that operate on the object’s data members. They define the behavior of the objects. |
| Access Modifiers | Keywords (public, private, protected) that control the visibility and accessibility of class members, crucial for encapsulation. |
| Constructor | A special member function automatically called when an object is created. Used for initialization. Can be overloaded. If none is defined, the compiler may generate a default one. |
| Destructor | A special member function (with a ~ prefix, e.g., ~Box()) automatically called when an object goes out of scope or is explicitly deleted. Used for cleanup (e.g., releasing resources). Follows the RAII principle. |
| Copy/Move Semantics | Constructors and assignment operators (operator=) that control how objects are copied or moved. Important for resource management (Rule of Zero/Three/Five). |
| Friend Functions/Classes | Non-member functions or other classes granted special access to the private and protected members of a class. |
this Pointer | Inside a non-static member function, this is a pointer to the current object instance itself. Used to disambiguate or return a reference/pointer to the object. |
| Static Members | Members (data or functions) associated with the class itself, not with individual objects. There’s only one copy per class. Accessed using the class name and scope resolution operator (e.g., ClassName::staticMember). |
| Const Correctness | Using the const keyword to indicate that member functions do not modify the object’s state, improving code safety and clarity. |
Understanding these concepts is vital for effective object-oriented programming in C++.