Experience Top-Rated Tutoring – 4.3/5 ★★★★★ by Parents & Students
Course Details
JOIN OUR

C++ Language

Book a free trial session and start your personalized learning journey with our expert tutors.

Send Us Your Enquiry To Get Started

Fill out the form below and one of our experts will contact you shortly

TutorX Smart Learning Dashboard

Everything You Need, All in One Place

TutorX Learning Platform

At The TutorX, we believe learning should be clear, focused, and at your fingertips. That’s why we’ve built a smart and user-friendly dashboard to empower every student on their academic journey. From live sessions and homework to performance tracking and resources—everything is seamlessly integrated to help you stay ahead with confidence.

  • View upcoming sessions and join with a single click.
  • Track your progress through weekly reports.
  • Access study materials tailored to your goals.
  • Get reminders so you never miss a session.
  • Connect with tutors and ask questions anytime.
Tutela Dashboard

C++ Tutorial | Learn C++ Programming Language

What is C++?

C++ is a general-purpose, object-oriented programming language developed by Bjarne Stroustrup at Bell Labs in 1979 as an extension of the C language. It was originally called "C with Classes" and was renamed C++ in 1983. C++ supports procedural, object-oriented, and generic programming paradigms, making it a multi-paradigm language. It is widely used in game development, system/software development, embedded systems, compilers, databases, and high-performance applications.

C++ adds several powerful features to C, including Classes and Objects, Inheritance, Polymorphism, Encapsulation, Abstraction, Templates, Exception Handling, and the Standard Template Library (STL). It is considered one of the most powerful and versatile programming languages in the world.

C vs C++ — Key Differences

C Language ✦ Procedural only ✦ No classes or objects ✦ No function overloading ✦ No exception handling ✦ No templates ✦ struct (no methods) ✦ printf / scanf for I/O ✦ malloc / free for memory ✦ .c file extension extends C++ Language ✦ Multi-paradigm (OOP + procedural) ✦ Classes and objects ✦ Function & operator overloading ✦ Try / catch exception handling ✦ Templates (generic programming) ✦ class (with methods + access) ✦ cin / cout for I/O ✦ new / delete for memory ✦ .cpp file extension

C++ is a superset of C — it includes all features of C and adds object-oriented and generic programming capabilities. C programs can generally be compiled as C++ programs. The biggest addition of C++ over C is the concept of Object-Oriented Programming (OOP) — which includes classes, objects, inheritance, polymorphism, and encapsulation.

Features of C++

1. Object-Oriented: Supports classes, objects, inheritance, polymorphism, and encapsulation. Makes code reusable, modular, and easier to manage.

2. Platform Independent: C++ code can be compiled and run on different platforms (Windows, Linux, macOS) with minimal changes.

3. Fast and Efficient: C++ is close to the hardware and gives direct memory control, making it one of the fastest high-level programming languages.

4. Rich Standard Library: Provides STL (Standard Template Library) with containers (vector, map, set), algorithms (sort, search), and iterators.

5. Templates: Generic programming allows writing functions and classes that work with any data type.

6. Exception Handling: try, catch, throw mechanism for handling runtime errors gracefully.

7. Function Overloading: Multiple functions with the same name but different parameters are allowed.

8. Operator Overloading: Existing operators like +, -, *, == can be redefined for user-defined types.

9. Pointer and Reference Support: Offers both C-style pointers and C++ references (&) for efficient memory operations.

10. Namespaces: Avoids name conflicts in large projects. The standard library lives in namespace std.

C++ OOPs Concepts

What is Object-Oriented Programming in C++?

Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around data (objects) rather than functions and logic. In C++, OOP is built on four main pillars: Encapsulation, Abstraction, Inheritance, and Polymorphism.

C++ OOP 4 Core Pillars Encapsulation Bundling data + methods in one unit (class) private / public access control Inheritance Child class acquires parent class properties class Dog : public Animal reuse of code Polymorphism One name, many forms function overloading virtual functions runtime dispatch Abstraction Show only essentials hide implementation abstract class pure virtual functions These 4 pillars together make C++ a powerful Object-Oriented language

Encapsulation: Wrapping data members and member functions together inside a class. Access is controlled using access specifiers — private, protected, and public. Data hiding is achieved by making variables private and accessing them through public getter/setter methods.

Abstraction: Showing only the necessary details to the user and hiding the internal implementation. Achieved using abstract classes (with pure virtual functions) and interfaces. Example: A car's steering wheel abstracts the complex steering mechanism beneath.

Inheritance: A derived (child) class acquires the properties and behaviors of a base (parent) class. Promotes code reusability. Types: Single, Multiple, Multilevel, Hierarchical, Hybrid. Example: class Dog : public Animal { };

Polymorphism: "One name, many forms." Allows the same function to behave differently based on the object. Compile-time polymorphism via function overloading and operator overloading. Runtime polymorphism via virtual functions and function overriding.

C++ Classes and Objects

What are Classes and Objects in C++?

A class in C++ is a user-defined data type that serves as a blueprint for creating objects. It bundles data (attributes/properties) and functions (methods/behaviors) together. An object is a real-world instance of a class — it has its own set of data members and can call member functions.

class Car private: string brand; int speed; public: void setBrand(string b); void setSpeed(int s); void display(); // Constructor Car(string b, int s); Blueprint / Template Object: car1 brand = "Toyota" speed = 120 Car car1("Toyota", 120); Object: car2 brand = "BMW" speed = 200 Car car2("BMW", 200); Object: car3 Car car3("Tesla", 250); Instances of class Car

Access Specifiers: private (accessible only inside the class), protected (accessible in class and derived classes), public (accessible everywhere). Members are private by default in a class and public by default in a struct.

Constructor: A special member function automatically called when an object is created. Same name as the class, no return type. Types: Default Constructor (no parameters), Parameterized Constructor (with parameters), Copy Constructor (creates a copy of an existing object).

Destructor: Automatically called when an object is destroyed/goes out of scope. Used to release resources. Syntax: ~ClassName() { }. Only one destructor per class — no parameters, no return type.

this Pointer: A special pointer available inside every non-static member function that points to the current object. Used to resolve conflicts between data members and parameters with the same name.

C++ Inheritance

What is Inheritance in C++?

Inheritance in C++ is a mechanism where a derived (child) class acquires the properties and behaviors of a base (parent) class. It promotes code reusability and establishes an "is-a" relationship between classes. Syntax: class DerivedClass : accessSpecifier BaseClass { };

Single Multiple Multilevel Hierarchical Hybrid Animal Dog Father Mother Child Animal Mammal Dog Shape Circle Rect Tri Hybrid Combination of 2 or more types above Uses virtual inheritance Inheritance Access Specifiers Base Member public inherit protected inherit private inherit public public protected private protected protected protected private

Single Inheritance: One derived class inherits from one base class. Example: class Dog : public Animal { };

Multiple Inheritance: One derived class inherits from more than one base class. Example: class Child : public Father, public Mother { };

Multilevel Inheritance: A chain of inheritance — class B inherits from A, class C inherits from B. Example: Animal → Mammal → Dog.

Hierarchical Inheritance: Multiple derived classes inherit from a single base class. Example: Shape → Circle, Rectangle, Triangle.

Hybrid Inheritance: Combination of two or more types. Can cause the Diamond Problem — solved using virtual inheritance.

C++ Polymorphism

What is Polymorphism in C++?

Polymorphism means "many forms." In C++, it allows functions and operators to behave differently based on the context. C++ supports two types of polymorphism: Compile-time (Static) Polymorphism and Runtime (Dynamic) Polymorphism.

Polymorphism in C++ Compile-time (Static) Resolved at compile time Function Overloading Same name, different parameters add(int,int) add(float,float) Operator Overloading Redefine operator for custom types Complex c3 = c1 + c2 using operator+() Runtime (Dynamic) Resolved at runtime via vtable Virtual Functions Base class pointer calls derived method virtual void speak() Pure Virtual Abstract class, must override virtual void f() = 0;

Function Overloading: Multiple functions with the same name but different parameter lists. The compiler decides which to call at compile time. Example: void print(int), void print(double), void print(string).

Operator Overloading: Redefining C++ operators (+, -, *, ==, etc.) for user-defined classes. Example: Complex c3 = c1 + c2; where + is overloaded using operator+(). Almost all operators can be overloaded except ::, .*, ., and ?:.

Virtual Functions: A function declared with virtual keyword in the base class. When called via a base class pointer pointing to a derived object, the derived class version is executed at runtime. Enables dynamic dispatch through the vtable (virtual function table).

Pure Virtual Functions and Abstract Classes: A function with = 0 is a pure virtual function. A class with at least one pure virtual function is an abstract class — it cannot be instantiated directly. All derived classes must override pure virtual functions. Used to enforce interfaces in C++.

C++ Templates

What are Templates in C++?

Templates in C++ allow writing generic functions and classes that work with any data type. They are the foundation of generic programming. The compiler generates the specific code for each data type when the template is used — called template instantiation. C++ supports Function Templates and Class Templates.

Function Template: A function that works for any data type.
template
T add(T a, T b) { return a + b; }
Usage: add(5, 3); // returns 8 — add(2.5, 1.5); // returns 4.0

Class Template: A class that works for any data type.
template
class Stack { T arr[100]; int top; public: void push(T); T pop(); };
Usage: Stack intStack; Stack strStack;

Template Specialization: Providing a specific implementation for a particular data type while keeping the generic version for others.

Template vs Macros: Templates are type-safe and checked by the compiler, unlike #define macros which are simple text substitution with no type checking.

C++ Exception Handling

What is Exception Handling in C++?

Exception handling in C++ is a mechanism to handle runtime errors gracefully without crashing the program. It uses three keywords: try (wraps code that might throw an exception), throw (signals an error), and catch (handles the thrown exception).

try { } // Risky code int result = a / b; if (b == 0) throw "Div by 0"; throw Exception "Div by 0" catch catch (const char* e) { } // Handle error cout << "Error: " << e; // catch(...) catches // all exceptions If no exception is thrown, catch block is skipped and program continues normally

try block: Contains code that might throw an exception. If an exception is thrown, control immediately jumps to the matching catch block.

throw: Used to signal an exception. Can throw any type — int, string, char*, or custom exception objects. Example: throw "Division by zero!"; or throw runtime_error("Error!");

catch block: Handles the thrown exception. Multiple catch blocks can handle different exception types. catch(...) catches all exceptions. Always catch by reference for polymorphic exception types.

Standard Exception Classes: C++ provides a hierarchy of exception classes in : runtime_error, logic_error, invalid_argument, out_of_range, overflow_error, underflow_error. All derived from std::exception.

Re-throwing: An exception can be re-thrown from a catch block using throw; (without argument) to pass it to an outer try-catch block.

C++ STL (Standard Template Library)

What is STL in C++?

The Standard Template Library (STL) is a powerful collection of template-based classes and functions in C++ that provide ready-to-use data structures and algorithms. STL consists of three main components: Containers, Algorithms, and Iterators.

C++ STL Components Containers Sequence: vector — dynamic array list — doubly linked list deque — double-ended queue Associative: map — key-value pairs set — unique elements multimap, multiset Algorithms Sorting: sort(), stable_sort() Searching: find(), binary_search() Modifying: copy(), fill(), replace() reverse(), rotate() count(), accumulate() Iterators Types: Input iterator Output iterator Forward iterator Bidirectional iterator Random access iterator Example: vector::iterator it

vector: Dynamic array that resizes automatically. Most commonly used STL container. push_back(), pop_back(), size(), at(), begin(), end().

map: Stores key-value pairs in sorted order (BST internally). Keys are unique. insert(), find(), erase(), count(). Unordered equivalent: unordered_map (hash table).

set: Stores unique elements in sorted order. No duplicates allowed. insert(), find(), erase(). Unordered equivalent: unordered_set.

stack: LIFO (Last In First Out) container adapter. push(), pop(), top(), empty(). Built on deque by default.

queue: FIFO (First In First Out) container adapter. push(), pop(), front(), back(), empty().

priority_queue: Heap-based container. Largest element is always at top. push(), pop(), top().

C++ Pointers and References

Pointers vs References in C++

C++ supports both C-style pointers and references. A pointer stores a memory address and can be reassigned or set to nullptr. A reference is an alias for an existing variable — it cannot be null, cannot be reassigned to reference a different variable, and is generally safer and cleaner than pointers.

42 num (0x200) int *ptr = &num Stores: 0x200 *ptr = 42 points to int &ref = num Alias — same address ref = 42 (same as num) alias of Pointer: Can be null, reassigned, pointer arithmetic Must use * to dereference Reference: Cannot be null or reassigned after init No dereferencing needed — cleaner syntax

new and delete: C++ uses new to allocate heap memory and delete to free it. int *p = new int(5); delete p; For arrays: int *arr = new int[10]; delete[] arr; Always pair new with delete to avoid memory leaks.

Smart Pointers (C++11+): unique_ptr (exclusive ownership, automatically deleted), shared_ptr (shared ownership with reference counting), weak_ptr (non-owning reference to shared_ptr). Defined in . Prefer smart pointers over raw pointers in modern C++.

nullptr: C++11 introduced nullptr to replace NULL and 0 as the null pointer constant. Always use nullptr instead of NULL in modern C++.

C++ File Handling

What is File Handling in C++?

C++ provides file I/O through the library which includes three classes: ofstream (output/write to file), ifstream (input/read from file), and fstream (both read and write). C++ file I/O is stream-based, using the same << and >> operators as cin and cout.

Writing to a file: ofstream file("output.txt"); file << "Hello, File!" << endl; file.close();

Reading from a file: ifstream file("input.txt"); string line; while(getline(file, line)) { cout << line << endl; } file.close();

File Open Modes: ios::in (read), ios::out (write), ios::app (append), ios::binary (binary mode), ios::trunc (truncate/overwrite), ios::ate (seek to end on open). Modes can be combined with | operator: ios::in | ios::out.

File Pointer Operations: seekg(pos) moves the get (read) pointer. seekp(pos) moves the put (write) pointer. tellg() returns current read position. tellp() returns current write position.

Error Checking: Always check if a file opened successfully: if(!file.is_open()) { cerr << "Error opening file"; }. Check eof() for end of file, fail() for failed operations, bad() for fatal errors.

C++ Namespace

What is a Namespace in C++?

A namespace in C++ is a declarative region that provides a scope to identifiers (variables, functions, classes) to avoid name conflicts in large programs. The C++ Standard Library is in the std namespace. All cout, cin, string, vector, etc. belong to std.

Defining a namespace:
namespace MySpace {
    int value = 10;
    void display() { cout << value; }
}
Usage: MySpace::value; MySpace::display();

using directive: using namespace std; imports all names from std so you can write cout instead of std::cout. Convenient but can cause conflicts in large projects — prefer using std::cout; in header files.

Nested namespaces: Namespaces can be nested. namespace Outer { namespace Inner { void func(); } } Usage: Outer::Inner::func(); C++17 allows: namespace Outer::Inner { void func(); }

Anonymous namespace: namespace { int secret = 5; } — variables in anonymous namespaces are local to the translation unit (like static in C). Useful for file-scope encapsulation.

C++ Programs

Important C++ Programs for Practice

1. Hello World in C++:
#include
using namespace std;
int main() { cout << "Hello, World!" << endl; return 0; }

2. Class with Constructor and Destructor:
class Student {
   string name; int age;
   public:
   Student(string n, int a) : name(n), age(a) { }
   ~Student() { cout << "Destroyed"; }
   void display() { cout << name << " " << age; }
};

3. Inheritance Example:
class Animal { public: virtual void speak() { cout << "..."; } };
class Dog : public Animal { public: void speak() override { cout << "Woof!"; } };
Animal *a = new Dog(); a->speak(); // prints "Woof!" via virtual dispatch

4. Function Template:
template
T maxVal(T a, T b) { return (a > b) ? a : b; }
cout << maxVal(10, 20) << endl; // 20
cout << maxVal(3.5, 2.1) << endl; // 3.5

5. STL vector and sort:
vector v = {5, 2, 8, 1, 9};
sort(v.begin(), v.end());
for(auto x : v) cout << x << " "; // 1 2 5 8 9

6. Exception Handling:
try { int a=10, b=0; if(b==0) throw runtime_error("Div by zero!"); cout << a/b; }
catch(runtime_error &e) { cerr << e.what(); }

7. Operator Overloading:
class Complex { public: float r, i;
Complex operator+(Complex c) { return {r+c.r, i+c.i}; } };
Complex c1={3,4}, c2={1,2}; Complex c3 = c1 + c2; // {4, 6}

8. Smart Pointer (unique_ptr):
unique_ptr p = make_unique(42);
cout << *p; // 42 — auto-deleted when out of scope

C++ Interview Questions and Answers

Top C++ Programming Interview Questions

Q1. What is the difference between struct and class in C++?
Ans: The only difference is default access — struct members are public by default, class members are private by default. Both support inheritance, constructors, destructors, and member functions.

Q2. What is a virtual function and why is it used?
Ans: A virtual function is declared with the virtual keyword in the base class. It enables runtime polymorphism — when called through a base class pointer, the derived class's overridden version executes. This is resolved via the vtable (virtual function table).

Q3. What is a pure virtual function and abstract class?
Ans: A pure virtual function is declared as virtual void func() = 0; A class with at least one pure virtual function is abstract — it cannot be instantiated. Derived classes must implement all pure virtual functions. Used to enforce interface contracts.

Q4. What is the difference between new/delete and malloc/free?
Ans: new calls the constructor and delete calls the destructor. malloc/free only allocate/free memory without calling constructors/destructors. new returns the correct type, malloc returns void*. Always use new/delete in C++ for objects.

Q5. What is copy constructor? When is it called?
Ans: A copy constructor creates a new object as a copy of an existing one. Syntax: ClassName(const ClassName &obj). Called when: passing object by value to a function, returning object by value from a function, initializing one object with another (Object b = a;).

Q6. What is the Diamond Problem and how is it solved in C++?
Ans: The diamond problem occurs in multiple inheritance when two parent classes inherit from the same grandparent — creating ambiguity about which grandparent's members to use. Solved using virtual inheritance: class B : virtual public A { }; class C : virtual public A { }; class D : public B, public C { };

Q7. What is a friend function in C++?
Ans: A friend function is a non-member function that has access to private and protected members of a class. Declared with the friend keyword inside the class: friend void display(MyClass obj); Friend functions break encapsulation but are useful for operator overloading and utility functions.

Q8. What is RAII in C++?
Ans: RAII stands for Resource Acquisition Is Initialization. Resources (memory, file handles, sockets) are tied to object lifetime — acquired in the constructor and released in the destructor. Smart pointers (unique_ptr, shared_ptr) and file streams (fstream) are classic RAII examples. Ensures automatic cleanup even when exceptions occur.

Q9. What is the difference between shallow copy and deep copy?
Ans: Shallow copy copies the pointer value (both objects point to same memory). Deep copy allocates new memory and copies the actual data. The default copy constructor performs a shallow copy. When a class has dynamically allocated members, always implement a custom deep copy constructor to avoid double-free errors.

Q10. What is move semantics and rvalue references (C++11)?
Ans: Move semantics allow transferring ownership of resources from one object to another without copying. Rvalue references (&&) bind to temporary objects. The move constructor and move assignment operator take rvalue references. std::move() converts an lvalue to rvalue to trigger move semantics. This greatly improves performance when working with large objects like vectors and strings.

C++ MCQ (Multiple Choice Questions)

C++ MCQs with Answers

Q1. Which of the following correctly defines a class in C++?
a) class MyClass; b) class MyClass { }; c) MyClass class { }; d) define class MyClass { };
Answer: b) class MyClass { };

Q2. What is the default access specifier in a C++ class?
a) public b) protected c) private d) none
Answer: c) private

Q3. Which keyword is used to prevent a class from being inherited?
a) static b) abstract c) final d) sealed
Answer: c) final — class MyClass final { };

Q4. What does the virtual keyword do in a function declaration?
a) Makes function inline b) Enables runtime polymorphism c) Prevents function overriding d) Makes function static
Answer: b) Enables runtime polymorphism

Q5. Which STL container provides O(1) average-time insertion and search?
a) map b) set c) vector d) unordered_map
Answer: d) unordered_map — uses hashing.

Q6. What is the output of: int a=5; cout << ++a << " " << a++;?
a) 5 6 b) 6 6 c) 6 7 d) 5 5
Answer: b) 6 6 — ++a increments first (6), a++ returns current value (6) then increments.

Q7. Which smart pointer allows only one owner of a resource?
a) shared_ptr b) weak_ptr c) unique_ptr d) auto_ptr
Answer: c) unique_ptr

Q8. What does the override keyword do in C++11?
a) Forces function inlining b) Confirms function overrides a virtual function c) Prevents function overloading d) Makes function static
Answer: b) Confirms function overrides a virtual function — compile error if no matching virtual exists.

Q9. Which header file is needed for file handling in C++?
a) b) c) d)
Answer: c)

Q10. What is the correct way to create a pure virtual function?
a) virtual void f(); b) void f() = 0; c) virtual void f() = 0; d) pure virtual void f();
Answer: c) virtual void f() = 0;

Instructor

Administrator

TUTORX ADMIN

Administrator

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

0 Rating
0 Reviews
93 Students
67 Courses

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Contact TutorX – We're Here to Help You Succeed

Reach out to us for inquiries, support, or more information about our personalized tutoring services

Get in touch

We are happy to hear from you. You can either fill out the form or send us an email.

Address

A1 220, 4th floor ,shushant lok phase 2 sector 55 gurgaon

Email

info@thetutorx.com

Phone

(+91)9013504886

Follow Us

Send Us Message

Shopping Cart

Loading...