CodeToLive

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++:

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:


#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:


#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

Next: Variables and Data Types