Introduction to C++
C++ is a general-purpose, object-oriented programming language developed by Bjarne Stroustrup in 1985. It is an extension of the C language and is widely used for system programming, game development, and applications requiring high performance.
Key Features of C++:
- Object-Oriented: C++ supports OOP principles like encapsulation, inheritance, and polymorphism.
- Efficient: C++ provides low-level memory manipulation and high performance.
- Rich Standard Library: C++ has a vast collection of built-in functions and templates.
- Portable: C++ programs can run on different platforms with minimal changes.
- Multi-Paradigm: C++ supports procedural, object-oriented, and generic programming.
Example: Hello World in C++
// C++ Hello World Program
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
This program includes the iostream
library and uses the std::cout
object to print "Hello, World!" to the console.
Object-Oriented Programming (OOP) in C++
C++ is designed to support object-oriented programming, which organizes software design around data (objects) rather than functions and logic. Key OOP concepts in C++ include:
- Classes and Objects: Classes are user-defined data types, and objects are instances of classes.
- Encapsulation: Bundling data and methods that operate on the data within a single unit.
- Inheritance: Creating new classes from existing ones to promote code reuse.
- Polymorphism: Allowing objects to be treated as instances of their parent class.
#include <iostream>
// Define a class
class Animal {
public:
void speak() {
std::cout << "Animal speaks!" << std::endl;
}
};
// Inherit from the Animal class
class Dog : public Animal {
public:
void speak() {
std::cout << "Dog barks!" << std::endl;
}
};
int main() {
Animal myAnimal;
Dog myDog;
myAnimal.speak(); // Output: Animal speaks!
myDog.speak(); // Output: Dog barks!
return 0;
}
Standard Template Library (STL)
The STL is a powerful library in C++ that provides a collection of template classes and functions. It includes:
- Containers: Data structures like vectors, lists, and maps.
- Algorithms: Functions for sorting, searching, and manipulating data.
- Iterators: Objects used to traverse containers.
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {5, 2, 9, 1, 5, 6};
// Sort the vector
std::sort(numbers.begin(), numbers.end());
// Print the sorted vector
for (int num : numbers) {
std::cout << num << " ";
}
return 0;
}
Best Practices
- Use Descriptive Names: Choose meaningful names for variables, functions, and classes.
- Follow OOP Principles: Encapsulate data, use inheritance wisely, and leverage polymorphism.
- Use STL: Prefer STL containers and algorithms for common tasks.
- Memory Management: Use smart pointers (
std::unique_ptr
,std::shared_ptr
) to manage dynamic memory safely. - Error Handling: Use exceptions to handle errors gracefully.