C++ Programming Syntax Guide

1. Basic Structure of a C++ Program

#include <iostream> int main() { std::cout << "Hello, World!" << std::endl; return 0; }

2. Data Types and Variables

int age = 25; double price = 19.99; char grade = 'A'; std::string name = "John";

3. Input and Output

std::cout << "Enter your name: "; std::cin >> name;

4. Control Structures

if (condition) { // code to execute if the condition is true } else { // code to execute if the condition is false }

5. Loops

for (int i = 0; i < 5; i++) { // code to repeat 5 times }

6. Functions

int add(int a, int b) { return a + b; }

7. Classes and Objects

class Person { public: std::string name; int age; void displayInfo() { std::cout << "Name: " << name << ", Age: " << age << std::endl; } }; Person person1; person1.name = "Alice"; person1.age = 30; person1.displayInfo();

8. Inheritance and Polymorphism

class Shape { public: virtual void draw() { // common drawing code } }; class Circle : public Shape { public: void draw() override { // circle-specific drawing code } };

9. Templates

template <typename T> T add(T a, T b) { return a + b; }

10. Standard Template Library (STL)

#include <vector> #include <algorithm> std::vector<int> numbers = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3}; std::sort(numbers.begin(), numbers.end());

11. Smart Pointers

#include <memory> std::shared_ptr<int> sharedPtr = std::make_shared<int>(42);

12. Exception Handling

try { // code that may throw an exception } catch (const std::exception &e) { // handle the exception }

13. Lambda Expressions

auto sum = [](int a, int b) { return a + b; }; int result = sum(3, 4);

14. Multithreading

#include <thread> void myFunction() { // code to run in a separate thread } std::thread myThread(myFunction);

15. File Handling

#include <fstream> std::ofstream outputFile("example.txt"); outputFile << "Hello, File!" << std::endl; outputFile.close();

16. Move Semantics

class MyString { public: // Move constructor MyString(MyString &&other) noexcept { // move data from 'other' to 'this' } };

17. Advanced Topics: Variadic Templates, Type Traits, SFINAE

template <typename... Args> void variadicFunction(Args... args) { // code for handling variable number of arguments }

0 Comment:

Post a Comment