Core Fundamentals and Concepts of C++ Programming
Overview of C++ and Its Primary Advantages
C++ is a high-level, general-purpose programming language created by Bjarne Stroustrup as an enhancement to the C language. It is recognized for its multi-paradigm support, allowing developers to utilize procedural, functional, and object-oriented programming (OOP) styles within a single codebase.
Key benefits include:
- Performance: As a compiled language, C++ provides near-hardware level efficiency, making it ideal for resource-intensive applications like game engines and operating systems.
- Granular Memory Control: Developers have the power to manage memory manually via
newanddelete, providing optimization opportunities that managed languages lack. - Standard Template Library (STL): A robust collection of data structures and algorithms that significantly accelerates development.
- Portability: Code written in C++ can be compiled for various architectures, ensuring wide cross-platform compatibility.
Classification of Data Types
C++ categorizes data into several distinct types to manage memory efficiently:
- Primitive Types: The building blocks, including
int(integers),char(characters),bool(boolean), anddouble/float(floating-point numbers). - Type Modifiers: Keywords like
signed,unsigned,short, andlongthat alter the range or size of primitive types. - Derived Types: Structures built from primitives, such as arrays, pointers, and references.
- User-Defined (Abstract) Types: Complex structures created using
class,struct,union, orenum. - Void: Represents the absence of a type, typically used for functions that do not return values.
The 'std' Namespace
The std (standard) namespace contains the entire C++ Standard Library. Using using namespace std; allows developers to call functions like cout directly. However, in professional environments, explicitly using std::cout is often preferred to avoid naming conflicts in the global scope.
Understanding References
A reference serves as an alias for an existing variable. Once initialized, it cannot be redirected to another variable.
double unitPrice = 45.5;
double &priceAlias = unitPrice; // priceAlias is now another name for unitPrice
priceAlias = 50.0; // Changes unitPrice to 50.0
Parameter Passing: Value vs. Reference
Pass by Value: A copy of the argument is created. Modifications inside the function do not affect the original variable.
void incrementValue(int val) {
val += 10;
}
Pass by Reference: The function receives a reference to the actual argument. Changes persist outside the function scope. This is more efficient for large objects as it avoids copying.
void incrementActual(int &val) {
val += 10;
}
The Concept of Tokens
A token is the smallest unit of a C++ program that a compiler recognizes. These include:
- Keywords: Reserved words like
if,while, andreturn. - Identifiers: Names given to variables, functions, and classes.
- Literals: Fixed values like
3.14or"Hello". - Operators: Symbols like
+,&, and->. - Punctuators: Formatting symbols like
;and{}.
C vs. C++: Key Distinctions
| Feature | C Language | C++ Language |
|---|---|---|
| Paradigm | Procedural only | Multi-paradigm (Procedural + OOP) |
| Overloading | Not supported | Supports function and operator overloading |
| Security | Data is often exposed | Data hiding through encapsulation |
| Standard | Subset of C++ | Superset of C |
Comparing 'struct' and 'class'
In C++, both can contain data and methods. The fundamental difference lies in default access levels:
- struct: Members and inheritance are
publicby default. Usually used for plain data containers. - class: Members and inheritance are
privateby default. Used for complex objects requiring encapsulation.
References vs. Pointers
| Aspect | Reference | Pointer |
|---|---|---|
| Re-assignment | Cannot be reasssigned | Can point to different addresses |
| Nullability | Must be initialized, cannot be null | Can be nullptr |
| Syntax | Uses . for members |
Uses -> for members |
| Indirection | Implicit | Requires dereferencing (*) |
Memory Allocation: new vs. malloc()
While both allocate heap memory, new is a C++ operator that calls constructors and returns a typed pointer. malloc() is a C-style function that simply allocates a block of bytes, returns a void*, and does not initialize objects.
Virtual and Pure Virtual Functions
- Virtual Function: A function in a base class that can be overridden in a derived class. It allows for runtime polymorphism.
- Pure Virtual Function: A function with no implementation in the base class (declared as
virtual void func() = 0;). Any class containing one becomes an Abstract Class and cannot be instantiated.
Classes and Objects
A Class is a blueprint or template, while an Object is a concrete instance of that blueprint.
class Smartphone {
public:
string model;
void boot() {
cout << model << " is starting up." << endl;
}
};
int main() {
Smartphone myPhone;
myPhone.model = "Pixel 7";
myPhone.boot();
}
The Pillars of Object-Oriented Programming
- Encapsulation: Bundling data and methods together while restricting direct access.
- Abstraction: Exposing only the necessary interface and hiding implementation complexities.
- Inheritance: Creating new classes based on existing ones to reuse code.
- Polymorphism: Allowing one interface to be used for a general class of actions (Static via overloading, Dynamic via overriding).
Constructors and Destructors
- Constructors: Special functions invoked automatically when an object is created to initialize its state.
- Destructors: Functions prefixed with
~that execute when an object goes out of scope, primari used to release resources (like memory or file handles). Destructors cannot be overloaded.
The Standard Template Library (STL)
The STL is built on four main pillars:
- Containers: Objects that store data (e.g.,
std::vector,std::map). - Algorithms: Functions for processing data (e.g.,
std::sort,std::find). - Iterators: Objects that act as bridges between containers and algorithms.
- Functors: Objects that can be treated like functions.
The 'volatile' and 'inline' Keywords
- volatile: Informs the compiler that a variable's value may change externally (e.g., by hardware), preventing the compiler from applying optimizations that assume the value is constant.
- inline: A suggestion to the compiler to replace function calls with the actual code body to reduce overhead. It is best used for small, frequently called functions.
Scope Resolution Operator (::)
The :: operator is used to:
- Access global variables when a local variable has the same name.
- Define class methods outside the class declaration.
- Access static members or elements within a namespace.
Friendship in C++
A friend function or class is granted access to the private and protected members of another class. While powerful, it should be used sparingly as it can weaken encapsulation.