C++Basicsbeginner

C++ Tutorial for Beginners with Simple Examples

Move from C to C++: input and output, strings, references, overloading, classes, objects and constructors with small programs.

Published
TL;DR – Quick Answer

C++ is C with extra features such as classes, objects, references, function overloading and a large standard library. If you know basic C, start with cout and cin, the string type and references, then learn classes, objects and constructors. Practise each idea with a small program.

On This Page

C++ is a programming language built on top of C. Bjarne Stroustrup created it in the early 1980s and first called it "C with Classes". It keeps almost everything from C and adds classes, objects and a rich standard library. Games, browsers, trading systems and many coding contest solutions are written in C++.

This C++ tutorial for beginners assumes you already know basic C: variables, if, loops, arrays and functions. If you do not, start with learn C programming step by step. Here we focus on what is new in C++.

Your first C++ program

Save this as hello.cpp:

#include <iostream>
using namespace std;

int main() {
    cout << "Hello, C++!" << endl;
    return 0;
}

Output:

Hello, C++!

Compile and run it with g++:

g++ hello.cpp -o hello
./hello

Compare it with C:

C C++ Meaning
#include <stdio.h> #include <iostream> Input and output library
printf("Hi\n"); cout << "Hi" << endl; Print text
scanf("%d", &x); cin >> x; Read input
File ends in .c File ends in .cpp Source file name

cout stands for "character output". The << operator sends data to it. endl ends the line. You can also write "\n", which is a little faster because it does not flush the output.

Input and output with cin and cout

#include <iostream>
using namespace std;

int main() {
    int age;
    double cgpa;
    cout << "Enter age and CGPA: ";
    cin >> age >> cgpa;
    cout << "Age: " << age << ", CGPA: " << cgpa << "\n";
    return 0;
}

Sample run:

Enter age and CGPA: 20 8.4
Age: 20, CGPA: 8.4

Notice two things. There are no format codes like %d, because cout and cin know the type of each variable. And there is no &, because cin takes the variable by reference.

The string type

In C, text is an array of char and you need functions such as strcpy and strlen. C++ gives you a string type that is much easier to use.

#include <iostream>
#include <string>
using namespace std;

int main() {
    string first = "Ravi";
    string last = "Kumar";
    string full = first + " " + last;

    cout << full << "\n";
    cout << "Length: " << full.length() << "\n";
    cout << "First letter: " << full[0] << "\n";
    return 0;
}

Output:

Ravi Kumar
Length: 10
First letter: R

You join strings with + and compare them with ==. To read a full line with spaces, use getline(cin, name); instead of cin >> name;, which stops at the first space.

bool and references

C++ has a built-in bool type with values true and false. You do not need any extra header.

A reference is another name for an existing variable. Any change through the reference changes the original. This makes it easy to write a swap function without pointers.

#include <iostream>
using namespace std;

void swapValues(int &a, int &b) {
    int temp = a;
    a = b;
    b = temp;
}

int main() {
    int x = 5, y = 9;
    swapValues(x, y);
    cout << "x = " << x << ", y = " << y << "\n";
    return 0;
}

Output:

x = 9, y = 5

The & in int &a means "a is a reference to an int". In C you would pass &x and use *a inside the function. C++ references do the same job with cleaner code.

Function overloading

In C, two functions cannot have the same name. In C++ they can, as long as their parameters differ. The compiler picks the right one from the arguments you pass.

#include <iostream>
using namespace std;

int area(int side) {
    return side * side;
}

int area(int length, int width) {
    return length * width;
}

int main() {
    cout << "Square: " << area(4) << "\n";
    cout << "Rectangle: " << area(4, 6) << "\n";
    return 0;
}

Output:

Square: 16
Rectangle: 24

Classes and objects

This is the biggest new idea in C++. A class is a blueprint. An object is one real thing made from that blueprint. A class groups data (called members or fields) and the functions that work on that data (called member functions or methods).

Think of a class Student as a blank admission form. Each filled form is an object.

#include <iostream>
#include <string>
using namespace std;

class Student {
public:
    string name;
    int marks;

    void show() {
        cout << name << " scored " << marks << "\n";
    }
};

int main() {
    Student s1;
    s1.name = "Anjali";
    s1.marks = 88;

    Student s2;
    s2.name = "Kiran";
    s2.marks = 74;

    s1.show();
    s2.show();
    return 0;
}

Output:

Anjali scored 88
Kiran scored 74

public: means code outside the class can use these members. Note the semicolon after the closing brace of the class. Forgetting it is a very common error.

Constructors and private data

Setting each field by hand is slow and risky. A constructor is a special function that runs when an object is created. It has the same name as the class and no return type.

Good classes also keep their data private so outside code cannot set wrong values. Outside code then uses public methods. This idea is called encapsulation.

#include <iostream>
#include <string>
using namespace std;

class BankAccount {
private:
    string owner;
    double balance;

public:
    BankAccount(string name, double amount) {
        owner = name;
        balance = amount;
    }

    void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }

    void show() {
        cout << owner << " has Rs. " << balance << "\n";
    }
};

int main() {
    BankAccount acc("Meena", 1000);
    acc.deposit(500);
    acc.deposit(-200);
    acc.show();
    return 0;
}

Output:

Meena has Rs. 1500

The negative deposit is ignored because deposit checks the value. If balance were public, any code could write acc.balance = -5000;. Private data protects the object from such mistakes.

Keyword Who can use the member
public Any code
private Only the class's own functions (default for class)
protected The class and classes that inherit from it

A quick look at vector

The C++ Standard Template Library (STL) gives ready-made containers. vector is an array that can grow.

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> marks = {70, 85, 90};
    marks.push_back(65);

    int total = 0;
    for (int m : marks) {
        total += m;
    }
    cout << "Count: " << marks.size() << ", Total: " << total << "\n";
    return 0;
}

Output:

Count: 4, Total: 310

push_back adds a value at the end. The loop for (int m : marks) is a range-based for loop, added in C++11. It visits each value in order.

Common beginner mistakes in C++

  • Missing semicolon after a class definition.
  • Using cin >> name for a full name with spaces. Use getline.
  • Mixing cin >> x and getline without clearing the leftover newline. Call cin.ignore() between them.
  • Making every member public. Keep data private and expose methods.
  • Reading past the end of an array or vector. C++ does not check plain [] access.

What to learn next in C++

  1. Inheritance and polymorphism, the other pillars of OOP. The ideas match the OOP concepts page, even though that page uses Java.
  2. Pointers and dynamic memory with new and delete.
  3. STL containers: vector, map, set, stack, queue.
  4. STL algorithms such as sort and find.
  5. Data structures and problem solving. The data structures and algorithms guide shows the path.

To see how C++ compares with the languages around it, read C vs C++ and Java vs C++. When you can write classes without help, practise with the OOPs interview questions.

Frequently Asked Questions

Should I learn C before C++?
It helps but is not required. If you already know C, most of the syntax for variables, loops and functions carries over. This tutorial assumes basic C knowledge.
What is the main difference between C and C++?
C is a procedural language. C++ adds object-oriented programming with classes and objects, plus features such as references, overloading, templates and the Standard Template Library.
Is C++ good for placements?
Many students use C++ for coding rounds because it is fast and the STL gives ready-made data structures. Check which languages each test allows, since this differs by company and platform.
What does using namespace std mean?
Names such as cout, cin and string live in a namespace called std. The line lets you write cout instead of std::cout. Larger projects often avoid it and write std:: in full.
Which compiler is used for C++?
Common choices are g++ (part of GCC), Clang and Microsoft Visual C++. On Windows, MinGW-w64 provides g++. Online compilers are fine for practice.

Want to Build Your Career in Java Full Stack with AI?

Join CodeBegun and train with working industry engineers — Explore the Java Full Stack program

Apply for Demo Class →
Siva Prasad Galaba
Founder, CodeBegun · Staff Engineer

Founder of CodeBegun. 15+ years building Java systems at companies like Crunchyroll. Teaches Java, Spring Boot and system design the way the industry actually works, and mentors students through projects, mock interviews and placement preparation.

Technically reviewed by CodeBegun Technical TeamLast reviewed 4 December 2026 LinkedIn
Chat with us