Introduction to C++
What is C++?
C++ is a general-purpose programming language developed by Bjarne Stroustrup at Bell Labs starting in 1979. It is an extension of the C programming language with object-oriented programming capabilities.
High Performance
C++ compiles to machine code, providing excellent runtime performance
Object-Oriented
Supports classes, objects, inheritance, and polymorphism
Memory Control
Direct memory management with pointers and references
Standard Library
Rich STL with containers, algorithms, and utilities
Your First C++ Program
Let's start with the traditional "Hello, World!" program:
Hello World Program
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
return 0;
}Code Explanation:
-
#include <iostream>- Includes the input/output stream library -
using namespace std;- Allows us to use standard library functions without std:: prefix -
int main()- The main function where program execution begins -
cout- Character output stream for printing to console -
return 0;- Indicates successful program termination
Basic Input and Output
C++ uses streams for input and output operations:
Input and Output Example
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
int age;
// Output
cout << "Enter your name: ";
// Input
getline(cin, name); // Read entire line including spaces
cout << "Enter your age: ";
cin >> age; // Read integer
// Output with variables
cout << "Hello, " << name << "!" << endl;
cout << "You are " << age << " years old." << endl;
return 0;
}Comments
Comments help document your code and are ignored by the compiler:
Comment Types
#include <iostream>
using namespace std;
/*
* This is a multi-line comment
* Used for longer explanations
* Author: Your Name
* Date: Today
*/
int main() {
// This is a single-line comment
cout << "Hello, World!" << endl; // Comment at end of line
/*
Multi-line comment can also be
used inline like this
*/
cout << "Learning C++!" << endl;
return 0; // Program ends successfully
}Compilation Process
C++ is a compiled language. Here's how to compile and run your programs:
Step 1: Write Code
Create a .cpp file (e.g., hello.cpp)
Step 2: Compile
Use g++ compiler: g++ -o hello hello.cpp
Step 3: Run
Execute: ./hello (Linux/Mac) or hello.exe (Windows)
Common Beginner Mistakes
Missing Semicolons
Every statement in C++ must end with a semicolon ;
Case Sensitivity
C++ is case-sensitive: cout β Cout β COUT
Missing Headers
Don't forget to #include necessary headers
Unmatched Braces
Every opening brace { must have a closing brace }