C++ Online Compiler

Output

# Ready to execute C++ code...
# Write your code above and click "Run"

Online C++ Compiler - Write, Run & Share C++ Code Instantly

Our online C++ compiler provides a powerful and convenient way to write, compile, and run C++ programs directly in your browser. Whether you're a beginner learning C++ programming or an experienced developer testing code snippets, our compiler offers a seamless coding experience with real-time output.

Why Use Our Online C++ Compiler?

  • No installation required - Code and run C++ programs directly from your browser
  • Fast compilation - Quick execution with our optimized backend
  • Real-time output - See results immediately after execution
  • User-friendly interface - Clean, intuitive design with syntax highlighting
  • Free to use - No registration or subscription needed
  • Mobile-friendly - Code on the go from any device
  • Share code easily - Generate shareable links to your code for collaboration or getting help

Getting Started with C++ Programming

C++ is a general-purpose programming language created by Bjarne Stroustrup as an extension of the C programming language. It was developed in 1985 and has since become one of the most popular and powerful programming languages, especially for system/software development, game development, and performance-critical applications.

Basic C++ Program Structure

#include <iostream>
using namespace std;

int main() {
    // Your code here
    cout << "Hello, World!";
    return 0;
}

Let's break down each part of this program:

  • #include <iostream>: This directive includes the standard input/output stream library, which provides functions like cout and cin.
  • using namespace std;: Allows us to use names for objects and variables from the standard library.
  • int main(): The entry point of the program where execution begins. The int indicates it returns an integer.
  • cout << "Hello, World!";: Outputs "Hello, World!" to the console.
  • return 0;: Indicates successful program completion.

Note: Every C++ program must have a main() function, which is the entry point of the program. The #include <iostream> line includes the standard input/output library which provides functions like cout and cin.

C++ Programming Basics

Variables and Data Types

C++ has several basic data types, each with specific sizes and ranges:

  • int: Typically 4 bytes, stores integers from -2,147,483,648 to 2,147,483,647
  • float: Typically 4 bytes, stores single-precision floating-point numbers
  • double: Typically 8 bytes, stores double-precision floating-point numbers
  • char: 1 byte, stores single characters
  • bool: 1 byte, stores true or false
  • string: For text (requires #include <string>)

C++ also supports short, long, unsigned, and other modifiers for additional flexibility.

Example of Variables in C++

int age = 25;
float price = 19.99f;
char grade = 'A';
bool is_valid = true;
string name = "John";

// Multiple variables in one line
int a = 1, b = 2, c = 3;

Control Structures

C++ provides standard control structures for decision making and loops:

If-Else Statement

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

For Loop

for (initialization; condition; increment) {
    // code to repeat
}

While Loop

int i = 0;
while (i < 5) {
    cout << i << " ";
    i++;
}

Switch Statement

int choice = 2;
switch (choice) {
    case 1:
        cout << "Option 1";
        break;
    case 2:
        cout << "Option 2";
        break;
    default:
        cout << "Invalid option";
}

Functions in C++

Functions allow you to organize your code into reusable blocks. They can return values or perform actions without returning anything (void functions).

// Function declaration
int addNumbers(int a, int b);
void greet();

int main() {
    int result = addNumbers(5, 3);
    cout << "Sum: " << result << endl;
    greet();
    return 0;
}

// Function definition
int addNumbers(int a, int b) {
    return a + b;
}

void greet() {
    cout << "Hello!" << endl;
}

Function overloading is a powerful C++ feature that allows multiple functions with the same name but different parameters.

Object-Oriented Programming in C++

C++ is known for its object-oriented programming (OOP) features:

Classes and Objects

class Car {
public:
    string brand;
    string model;
    int year;
    
    void honk() {
        cout << "Beep beep!" << endl;
    }
};

int main() {
    Car myCar;
    myCar.brand = "Toyota";
    myCar.model = "Corolla";
    myCar.year = 2020;
    
    myCar.honk();
    return 0;
}

Constructors

class Car {
public:
    string brand;
    string model;
    int year;
    
    Car(string b, string m, int y) {
        brand = b;
        model = m;
        year = y;
    }
};

int main() {
    Car myCar("Toyota", "Corolla", 2020);
    return 0;
}

Inheritance

class Vehicle {
public:
    string brand = "Ford";
    void honk() {
        cout << "Beep!" << endl;
    }
};

class Car: public Vehicle {
public:
    string model = "Mustang";
};

int main() {
    Car myCar;
    myCar.honk();
    cout << myCar.brand + " " + myCar.model << endl;
    return 0;
}

Polymorphism

class Animal {
public:
    virtual void animalSound() {
        cout << "The animal makes a sound" << endl;
    }
};

class Pig: public Animal {
public:
    void animalSound() {
        cout << "The pig says: wee wee" << endl;
    }
};

class Dog: public Animal {
public:
    void animalSound() {
        cout << "The dog says: bow wow" << endl;
    }
};

int main() {
    Animal* animals[3];
    animals[0] = new Animal();
    animals[1] = new Pig();
    animals[2] = new Dog();
    
    for (int i = 0; i < 3; i++) {
        animals[i]->animalSound();
    }
    
    return 0;
}

Tip: C++ supports all four pillars of OOP: Encapsulation, Abstraction, Inheritance, and Polymorphism. Mastering these concepts is key to becoming proficient in C++.

Standard Template Library (STL)

The STL provides powerful template classes and functions for common data structures and algorithms:

Vectors (Dynamic Arrays)

#include <vector>

vector<int> numbers = {1, 2, 3, 4, 5};
numbers.push_back(6); // Add element
numbers.pop_back();   // Remove last element

for (int num : numbers) {
    cout << num << " ";
}

Maps (Key-Value Pairs)

#include <map>

map<string, int> ages;
ages["John"] = 25;
ages["Alice"] = 30;

for (auto& pair : ages) {
    cout << pair.first << " is " << pair.second << " years old" << endl;
}

Algorithms

#include <algorithm>

vector<int> numbers = {5, 2, 8, 1, 9};
sort(numbers.begin(), numbers.end());

if (binary_search(numbers.begin(), numbers.end(), 8)) {
    cout << "8 found in the vector" << endl;
}

Memory Management in C++

C++ gives programmers direct control over memory through pointers and dynamic memory allocation:

Pointers

int var = 20;
int* ptr = &var;
cout << "Value of var: " << var << endl;
cout << "Address of var: " << &var << endl;
cout << "Value of ptr: " << ptr << endl;
cout << "Value pointed by ptr: " << *ptr << endl;

Dynamic Memory Allocation

int* arr = new int[5];  // Allocate memory
for (int i = 0; i < 5; i++) {
    arr[i] = i;
}
delete[] arr;  // Free memory

Smart Pointers (Modern C++)

#include <memory>

unique_ptr<int> ptr(new int(10));
cout << *ptr << endl;  // No need to manually delete

Important: Always free dynamically allocated memory with delete (for single objects) or delete[] (for arrays) to prevent memory leaks. Modern C++ (C++11 and later) provides smart pointers (unique_ptr, shared_ptr) that automatically manage memory.

File Handling in C++

C++ provides fstream for working with files:

#include <fstream>

// Writing to a file
ofstream outFile("example.txt");
if (outFile.is_open()) {
    outFile << "Hello, File!";
    outFile.close();
}

// Reading from a file
ifstream inFile("example.txt");
if (inFile.is_open()) {
    string line;
    while (getline(inFile, line)) {
        cout << line << endl;
    }
    inFile.close();
}

Frequently Asked Questions

How do I take user input in C++?

You can use the cin object to take user input. For example:

int age;
cout << "Enter your age: ";
cin >> age;
What is the difference between C and C++?

C is a procedural programming language, while C++ is a multi-paradigm language that supports procedural, object-oriented, and generic programming. C++ is backward compatible with C but adds many features like classes, objects, inheritance, polymorphism, templates, exception handling, and the Standard Template Library (STL).

How do I compile C++ code on my computer?

You'll need a C++ compiler like g++. Save your code with a .cpp extension (e.g., program.cpp) and compile with: g++ program.cpp -o program. Then run the executable: ./program (on Linux/Mac) or program.exe (on Windows).

What are the advantages of learning C++?

C++ offers high performance, low-level memory manipulation, object-oriented features, generic programming, portability, and is widely used in system/software development, game development, embedded systems, and high-performance applications. It's also a great language for understanding computer science fundamentals.

What is the difference between C++ and C#?

C++ is a compiled language that gives low-level control, while C# is a managed language that runs on the .NET framework. C++ is typically used for performance-critical applications, while C# is often used for Windows applications, web services, and game development with Unity.

How do I handle strings in C++?

C++ offers the string class from the Standard Library (#include <string>), which is much easier to use than C-style character arrays:

string greeting = "Hello";
greeting += " World!";
cout << greeting.length(); // Get length
cout << greeting.substr(0, 5); // Get substring
What are references in C++?

References are aliases for existing variables. They must be initialized when declared and cannot be changed to refer to another variable:

int x = 10;
int& ref = x;  // ref is a reference to x
ref = 20;      // Changes x to 20

Advanced C++ Programming Concepts

Once you've mastered the basics, you can explore these advanced topics:

  • Templates: For generic programming
  • template <typename T>
    T max(T a, T b) {
        return (a > b) ? a : b;
    }
  • Exception Handling: Using try, catch, and throw
  • try {
        if (x == 0) throw "Division by zero!";
        cout << 10 / x;
    } catch (const char* msg) {
        cerr << msg << endl;
    }
  • Lambda Expressions: Anonymous functions
  • auto sum = [](int a, int b) { return a + b; };
    cout << sum(5, 3);
  • Move Semantics: For efficient resource management
  • Multithreading: Using #include <thread>
  • Smart Pointers: unique_ptr, shared_ptr, weak_ptr

Remember: Our online C++ compiler is perfect for practicing all these concepts. Try writing code examples for each topic to reinforce your learning!

Common C++ Programming Mistakes

Be aware of these common pitfalls when learning C++:

  • Memory leaks (allocating memory but not freeing it)
  • Dangling pointers (pointers pointing to freed memory)
  • Buffer overflows (writing beyond array bounds)
  • Forgetting to handle exceptions
  • Shallow copying when deep copy is needed
  • Not initializing variables before use
  • Using using namespace std; in header files
  • Not following the Rule of Three/Five/Zero for resource management

Tip: Use tools like valgrind and address sanitizers to catch memory issues.

C++ Standard Library

The C++ Standard Library provides many useful components:

  • Containers: vector, list, map, set, etc.
  • Algorithms: sort, find, transform, etc.
  • Iterators: For traversing containers
  • Strings: string class for text manipulation
  • I/O Streams: cin, cout, file streams
  • Smart Pointers: For automatic memory management
  • Thread Support: For multithreading

Our online C++ compiler supports all standard C++ library features, so you can experiment freely.

Learning Resources

To continue your C++ programming journey, check out these resources:

  • Books: "The C++ Programming Language" by Bjarne Stroustrup, "Effective C++" by Scott Meyers, "C++ Primer" by Lippman
  • Online courses: Coursera, edX, Udemy offer C++ programming courses
  • Practice problems: LeetCode, HackerRank, CodeChef
  • Open source projects: Study and contribute to C++ projects on GitHub
  • Documentation: cppreference.com, C++ Core Guidelines

Our online C++ compiler is the perfect tool to practice what you learn from these resources. The more you code, the better you'll become!