Measures Concepts
GitHub icon

C++

C++ - Programming language

< >

C++ is a programming language created in 1985 by Bjarne Stroustrup.

#7on PLDB 39Years Old 2mRepos

Try now: Riju ยท Replit

C++ ( pronounced cee plus plus) is a general-purpose programming language. It has imperative, object-oriented and generic programming features, while also providing facilities for low-level memory manipulation. It was designed with a bias toward system programming and embedded, resource-constrained and large systems, with performance, efficiency and flexibility of use as its design highlights. Read more on Wikipedia...


Example from Compiler Explorer:
// Type your code here, or load an example. int square(int num) { return num * num; }
Example from Riju:
#include <iostream> int main() { std::cout << "Hello, world!" << std::endl; return 0; }
Example from hello-world:
#include <iostream> int main() { std::cout << "Hello World" << std::endl; }
// Hello World in C++ (pre-ISO) #include <iostream.h> main() { cout << "Hello World!" << endl; return 0; }
Example from Linguist:
#include <cstdint> namespace Gui { }
Example from Wikipedia:
1 #include <iostream> 2 #include <vector> 3 #include <stdexcept> 4 5 int main() { 6 try { 7 std::vector<int> vec{3, 4, 3, 1}; 8 int i{vec.at(4)}; // Throws an exception, std::out_of_range (indexing for vec is from 0-3 not 1-4) 9 } 10 // An exception handler, catches std::out_of_range, which is thrown by vec.at(4) 11 catch (std::out_of_range &e) { 12 std::cerr << "Accessing a non-existent element: " << e.what() << '\n'; 13 } 14 // To catch any other standard library exceptions (they derive from std::exception) 15 catch (std::exception &e) { 16 std::cerr << "Exception thrown: " << e.what() << '\n'; 17 } 18 // Catch any unrecognised exceptions (i.e. those which don't derive from std::exception) 19 catch (...) { 20 std::cerr << "Some fatal error\n"; 21 } 22 }
#define #defined #elif #else #endif #error #if #ifdef #ifndef #include #line #pragma #undef alignas alignof and and_eq asm atomic_cancel atomic_commit atomic_noexcept auto bitand bitor bool break case catch char char16_t char32_t class compl concept const constexpr const_cast continue decltype default delete do double dynamic_cast else enum explicit export extern false final float for friend goto if inline int import long module mutable namespace new noexcept not not_eq nullptr operator or or_eq override private protected public register reinterpret_cast requires return short signed sizeof static static_assert static_cast struct switch synchronized template this thread_local throw transaction_safe transaction_safe_dynamic true try typedef typeid typename union unsigned using virtual void volatile wchar_t while xor xor_eq

Language features

Feature Supported Token Example
Access Modifiers โœ“
Exceptions โœ“
Classes โœ“
Threads โœ“
Virtual function โœ“
class Animal {
 public:
  // Intentionally not virtual:
  void Move(void) {
    std::cout << "This animal moves in some way" << std::endl;
  }
  virtual void Eat(void) = 0;
};

// The class "Animal" may possess a definition for Eat if desired.
class Llama : public Animal {
 public:
  // The non virtual function Move is inherited but not overridden.
  void Eat(void) override {
    std::cout << "Llamas eat grass!" << std::endl;
  }
};
Templates โœ“
template 
Vector& Vector::operator+=(const Vector& rhs)
{
    for (int i = 0; i < length; ++i)
        value[i] += rhs.value[i];
    return *this;
}
Operator Overloading โœ“
Multiple Inheritance โœ“
Namespaces โœ“
#include 
using namespace std;

// Variable created inside namespace
namespace first
{
  int val = 500;
}
 
// Global variable
int val = 100;
// Ways to do it: https://en.cppreference.com/w/cpp/language/namespace
namespace ns_name { declarations }
inline namespace ns_name { declarations }
namespace { declarations }
ns_name::name
using namespace ns_name;
using ns_name::name;
namespace name = qualified-namespace ;
namespace ns_name::inline(since C++20)(optional) name { declarations } 
Function Overloading โœ“
// volume of a cube
int volume(const int s) {
 return s*s*s;
}
// volume of a cylinder
double volume(const double r, const int h) {
  return 3.1415926*r*r*static_cast(h);
}
Iterators โœ“
std::vector items;
items.push_back(5);  // Append integer value '5' to vector 'items'.
items.push_back(2);  // Append integer value '2' to vector 'items'.
items.push_back(9);  // Append integer value '9' to vector 'items'.

for (auto it = items.begin(); it != items.end(); ++it) {  // Iterate through 'items'.
  std::cout << *it;  // And print value of 'items' for current index.
}
Constructors โœ“
class Foobar {
 public:
  Foobar(double r = 1.0,
         double alpha = 0.0)  // Constructor, parameters with default values.
      : x_(r * cos(alpha))    // <- Initializer list
  {
    y_ = r * sin(alpha);  // <- Normal assignment
  }

 private:
  double x_;
  double y_;
};
Foobar a,
       b(3),
       c(5, M_PI/4);
Single Dispatch โœ“
Partial Application โœ“
// http://www.cplusplus.com/reference/functional/bind/
// bind example
#include      // std::cout
#include    // std::bind

// a function: (also works with function object: std::divides my_divide;)
double my_divide (double x, double y) {return x/y;}

struct MyPair {
  double a,b;
  double multiply() {return a*b;}
};

int main () {
  using namespace std::placeholders;    // adds visibility of _1, _2, _3,...

  // binding functions:
  auto fn_five = std::bind (my_divide,10,2);               // returns 10/2
  std::cout << fn_five() << '\n';                          // 5

  auto fn_half = std::bind (my_divide,_1,2);               // returns x/2
  std::cout << fn_half(10) << '\n';                        // 5

  auto fn_invert = std::bind (my_divide,_2,_1);            // returns y/x
  std::cout << fn_invert(10,2) << '\n';                    // 0.2

  auto fn_rounding = std::bind (my_divide,_1,_2);     // returns int(x/y)
  std::cout << fn_rounding(10,3) << '\n';                  // 3

  MyPair ten_two {10,2};

  // binding members:
  auto bound_member_fn = std::bind (&MyPair::multiply,_1); // returns x.multiply()
  std::cout << bound_member_fn(ten_two) << '\n';           // 20

  auto bound_member_data = std::bind (&MyPair::a,ten_two); // returns ten_two.a
  std::cout << bound_member_data() << '\n';                // 10

  return 0;
}
Scientific Notation โœ“
Conditionals โœ“
Constants โœ“
While Loops โœ“
Case Sensitivity โœ“
Assignment โœ“ =
Switch Statements โœ“
switch(expression) {
   case true  :
      break;
   default :
   //
   break;
}
Print() Debugging โœ“ std::cout
MultiLine Comments โœ“ /* */
/* A comment
*/
Line Comments โœ“ //
// A comment
Increment and decrement operators โœ“
Zero-based numbering โœ“
Variadic Functions โœ“
double average(int count, ...)
{
 //
}
Operators โœ“
1 + 1;
Manual Memory Management โœ“
#include 
#include 
int main(void)
{
  int *poin = malloc(4);
  free(poin);
}
Macros โœ“
// https://learn.microsoft.com/en-us/cpp/preprocessor/macros-c-cpp?redirectedfrom=MSDN&view=msvc-170
// https://gcc.gnu.org/onlinedocs/cpp/Macro-Arguments.html
#define min(X, Y)  ((X) < (Y) ? (X) : (Y))
  x = min(a, b);          โ†’  x = ((a) < (b) ? (a) : (b));
  y = min(1, 2);          โ†’  y = ((1) < (2) ? (1) : (2));
  z = min(a + 28, *p);    โ†’  z = ((a + 28) < (*p) ? (a + 28) : (*p));
Integers โœ“
int pldb = 80766866;
File Imports โœ“
//  If a header file is included within <>, the preprocessor will search a predetermined directory path to locate the header file. If the header file is enclosed in "", the preprocessor will look for the header file in the same directory as the source file.
#include 
#include "stdio.h"
Type Casting โœ“
double da = 3.3;
double db = 3.3;
double dc = 3.4;
int result = (int)da + (int)db + (int)dc; //result == 9
Directives โœ“
#include 
#define height 10
#ifdef
#endif
#if
#else
#ifndef
#undef
#pragma
Gotos โœ“
// C/C++ program to check if a number is 
// even or not using goto statement 
#include  
using namespace std; 
  
// function to check even or not 
void checkEvenOrNot(int num) 
{ 
    if (num % 2 == 0) 
        goto even; // jump to even 
    else
        goto odd; // jump to odd 
  
even: 
    cout << num << " is evenn"; 
    return; // return if even 
odd: 
    cout << num << " is oddn"; 
} 
  
// Driver program to test above function 
int main() 
{ 
    int num = 26; 
    checkEvenOrNot(num); 
    return 0; 
}
Structs โœ“
struct account {
  int account_number;
  char *first_name;
  char *last_name;
  float balance;
};
Comments โœ“
/* hello world */
// hi
Symbol Tables โœ“
// Declare an external function
extern double bar(double x);

// Define a public function
double foo(int count)
{
    double  sum = 0.0;

    // Sum all the values bar(1) to bar(count)
    for (int i = 1;  i <= count;  i++)
        sum += bar((double) i);
    return sum;
}
// Symbol Table:
// Symbol name|Type|Scope
// bar|function, double|extern
// x|double|function parameter
// foo|function, double|global
// count|int|function parameter
// sum|double|block local
// i|int|for-loop statement
Bitwise Operators โœ“
int i = 4; /* bit pattern equivalent is binary 100 */
int j = i << 2; /* makes it binary 10000, which multiplies the original number by 4 i.e. 16 */
Assert Statements โœ“
#include 
int i, a[10];
for (i = 0; i < 10; ++i)
  {
  assert(0 <= i && i < 10);
  a[i] = 10-i;
  }
for (i = 0; i < 10; ++i)
  {
  assert(0 <= i && i < 10);
  assert(0 <= a[i] && a[i] < 10);
  a[a[i]] = a[i];
  }
Strings โœ“ "
"hello world"
Pointers โœ“
int *ptr;
Ternary operators โœ“
#include 
int main(void) { printf("%d", 1 ? 1 : 0); }
Characters โœ“
char character = 'P';
Booleans โœ“ true false
Enums โœ“
enum Gender {
  Male,
  Female,
};
Magic Getters and Setters X
Fixed Point Numbers X
Case Insensitive Identifiers X
Semantic Indentation X
Garbage Collection X
Regular Expression Syntax Sugar X
Variable Substitution Syntax X

View source

- Build the next great programming language ยท Search ยท Add Language ยท Features ยท Creators ยท Resources ยท About ยท Blog ยท Acknowledgements ยท Queries ยท Stats ยท Sponsor ยท Day 605 ยท feedback@pldb.io ยท Logout