C++ Programming: Concepts, Examples and Object-Oriented Programming
Learn the fundamentals of C++, including syntax, variables, control statements, functions, classes, inheritance, polymorphism, templates, exceptions, and file handling.
1. Introduction to C++
C++ is a general-purpose programming language developed by Bjarne Stroustrup. It began as an extension of the C programming language and is widely used for system software, game development, embedded systems, desktop applications, high-performance programs, and competitive programming.
C++ gives programmers control over memory and system resources while also supporting high-level features such as classes, templates, inheritance, and polymorphism.
Important Characteristics of C++
- General-purpose: C++ can be used to build many kinds of software.
- Compiled language: C++ source code is normally compiled into machine code before execution.
- High performance: C++ is useful where speed and efficient resource use are important.
- Object-oriented support: C++ supports classes, objects, inheritance, encapsulation, and polymorphism.
- Generic programming: Templates allow code to work with different data types.
- Portable: Well-written standard C++ code can usually be compiled on different operating systems.
2. Your First C++ Program
The following program displays a message on the screen:
#include <iostream>
int main() {
std::cout << "Hello, World!\n";
return 0;
}
Understanding the Program
#include <iostream>provides input and output stream facilities.main()is the function where a C++ program begins execution.std::coutdisplays output on the screen.<<is the stream insertion operator.return 0;indicates successful program completion. Inmain(), reaching the closing brace also returns 0 automatically.
std::cout, std::string, and other
names with the std:: prefix in learning examples. Avoid writing
using namespace std; in global scope.
3. C++ Tokens
A token is one of the smallest meaningful elements of a C++ program. The compiler uses tokens to understand the structure of the source code.
- Keywords: Reserved words such as
int,class,if, andreturn. - Identifiers: Names given to variables, functions, classes, and other program elements.
- Literals: Fixed values such as
10,3.14,'A', and"Hello". - Operators: Symbols used to perform operations, such as
+,==, and&&. - Punctuators: Symbols such as parentheses, braces, commas, and semicolons.
4. Data Types, Variables and Constants
A data type tells the compiler what kind of value a variable is expected to store. Choosing an appropriate type helps a program store and process data correctly.
| Data Type | Used For | Example |
|---|---|---|
int | Whole numbers | int age = 25; |
float | Decimal numbers | float price = 10.5f; |
double | Decimal values requiring more precision | double pi = 3.14159; |
char | A single character | char grade = 'A'; |
bool | True or false values | bool passed = true; |
std::string | Text | std::string name = "Rahul"; |
Variables
A variable is a named storage location whose value can change during program execution.
int marks = 85;
marks = 90;
Constants
A constant is a value that should not change after it is initialised.
const double pi = 3.14159;
5. C++ Operators
Operators are symbols used to perform operations on values and variables.
- Arithmetic operators:
+,-,*,/,% - Relational operators:
==,!=,>,<,>=,<= - Logical operators:
&&,||,! - Assignment operators:
=,+=,-=,*=,/= - Increment and decrement:
++,-- - Bitwise operators:
&,|,^,~,<<,>> - Conditional operator:
?:
Arithmetic Example
Suppose a = 10 and b = 5.
| Expression | Result |
|---|---|
a + b | 15 |
a - b | 5 |
a * b | 50 |
a / b | 2 |
a % b | 0 |
7 / 2 produces 3.
6. Control Statements
Control statements determine which part of a program executes and how often a block of code repeats.
if-else Statement
#include <iostream>
int main() {
int marks = 75;
if (marks >= 40) {
std::cout << "Pass\n";
} else {
std::cout << "Fail\n";
}
}
for Loop
#include <iostream>
int main() {
for (int i = 1; i <= 5; ++i) {
std::cout << i << " ";
}
}
while Loop
#include <iostream>
int main() {
int i = 1;
while (i <= 5) {
std::cout << i << " ";
++i;
}
}
switch Statement
#include <iostream>
int main() {
int choice = 2;
switch (choice) {
case 1:
std::cout << "Add\n";
break;
case 2:
std::cout << "Edit\n";
break;
default:
std::cout << "Invalid choice\n";
}
}
7. Functions in C++
A function is a block of code designed to perform a specific task. Functions make programs easier to organise, test, reuse, and maintain.
#include <iostream>
int add(int firstNumber, int secondNumber) {
return firstNumber + secondNumber;
}
int main() {
int result = add(10, 20);
std::cout << result << "\n";
}
Call by Value
In call by value, a function receives a copy of the argument. Changing the parameter does not change the original variable.
#include <iostream>
void changeValue(int value) {
value = 100;
}
int main() {
int number = 10;
changeValue(number);
std::cout << number << "\n"; // Output: 10
}
Call by Reference
In call by reference, a function receives a reference to the original variable. Changes made through the reference affect the original value.
#include <iostream>
void changeValue(int& value) {
value = 100;
}
int main() {
int number = 10;
changeValue(number);
std::cout << number << "\n"; // Output: 100
}
8. Classes and Objects
A class is a user-defined type that groups data and functions together. An object is an instance of a class.
#include <iostream>
#include <string>
class Student {
public:
std::string name;
int marks;
void display() const {
std::cout << name << ": " << marks << "\n";
}
};
int main() {
Student student;
student.name = "Rahul";
student.marks = 85;
student.display();
}
In this example, Student is the class and student is an object.
9. Object-Oriented Programming Concepts
C++ supports object-oriented programming. The following four principles are commonly taught as the main OOP concepts.
Encapsulation
Encapsulation means keeping related data and functions together while controlling access to the data. Private data members help prevent invalid changes from outside a class.
Abstraction
Abstraction means exposing important functionality while hiding unnecessary implementation details. For example, a user can drive a car without knowing how every engine component works.
Inheritance
Inheritance allows a derived class to reuse and extend features of an existing base class.
#include <iostream>
class Animal {
public:
void eat() const {
std::cout << "Eating\n";
}
};
class Dog : public Animal {
public:
void bark() const {
std::cout << "Barking\n";
}
};
int main() {
Dog dog;
dog.eat();
dog.bark();
}
Polymorphism
Polymorphism means “many forms”. In C++, a common interface can behave differently depending on the actual object being used. Function overloading is compile-time polymorphism, while virtual functions support runtime polymorphism.
10. Constructors
A constructor is a special member function that is called automatically when an object is created. It is usually used to initialise data members.
class Rectangle {
private:
int length;
int width;
public:
Rectangle() : length(0), width(0) {
}
Rectangle(int inputLength, int inputWidth)
: length(inputLength), width(inputWidth) {
}
int area() const {
return length * width;
}
};
Copy Constructor
A copy constructor creates an object using another object of the same class. The compiler can generate a copy constructor automatically in many simple cases.
Rectangle firstRectangle(10, 5);
Rectangle secondRectangle = firstRectangle;
11. Function Overloading and Runtime Polymorphism
Function Overloading
Function overloading allows multiple functions to have the same name when their parameter lists are different.
int add(int firstNumber, int secondNumber) {
return firstNumber + secondNumber;
}
double add(double firstNumber, double secondNumber) {
return firstNumber + secondNumber;
}
Runtime Polymorphism
Runtime polymorphism is commonly implemented with virtual functions. A base-class reference or pointer can refer to a derived object, and the correct overridden function is selected at runtime.
#include <iostream>
class Animal {
public:
virtual ~Animal() = default;
virtual void sound() const {
std::cout << "Animal sound\n";
}
};
class Dog : public Animal {
public:
void sound() const override {
std::cout << "Dog barks\n";
}
};
int main() {
Dog dog;
Animal& animal = dog;
animal.sound();
}
The call to animal.sound() runs the Dog version because
sound() is virtual and the referenced object is a Dog.
12. Templates in C++
Templates support generic programming. They allow a function or class to work with different compatible data types without rewriting the same logic.
#include <iostream>
template <typename T>
T maximum(T firstValue, T secondValue) {
return (firstValue > secondValue) ? firstValue : secondValue;
}
int main() {
std::cout << maximum(10, 20) << "\n";
std::cout << maximum(2.5, 3.7) << "\n";
}
13. Exception Handling
Exception handling provides a way to deal with unexpected or exceptional situations
while a program is running. C++ commonly uses try, throw,
and catch.
#include <iostream>
#include <stdexcept>
int main() {
int numerator = 10;
int denominator = 0;
try {
if (denominator == 0) {
throw std::runtime_error("Division by zero");
}
std::cout << numerator / denominator << "\n";
} catch (const std::runtime_error& error) {
std::cout << "Error: " << error.what() << "\n";
}
}
trycontains code that may cause an exception.throwreports an exceptional condition.catchhandles the exception.
14. File Handling in C++
C++ uses file streams to read from and write to files. The main file stream classes are
std::ofstream, std::ifstream, and std::fstream.
Writing to a File
#include <fstream>
int main() {
std::ofstream outputFile("example.txt");
if (!outputFile) {
return 1;
}
outputFile << "Hello from C++\n";
}
Reading from a File
#include <fstream>
#include <iostream>
#include <string>
int main() {
std::ifstream inputFile("example.txt");
if (!inputFile) {
std::cout << "Unable to open file.\n";
return 1;
}
std::string text;
std::getline(inputFile, text);
std::cout << text << "\n";
}
Always check whether a file opened successfully. A file may be missing, inaccessible, or located at a different path.
15. Important C++ Concepts for Revision
- Class: A user-defined type that groups data and functions.
- Object: An instance of a class.
- Constructor: A special member function that initialises an object.
- Inheritance: A mechanism through which one class derives features from another class.
- Polymorphism: Using a common interface with different implementations.
- Encapsulation: Keeping data and related functions together while controlling access.
- Abstraction: Hiding unnecessary implementation details.
- Template: A feature for writing generic code that works with different types.
- Exception: An unusual condition handled using C++ exception mechanisms.
- Reference: Another name for an existing variable or object.
16. Practice Questions
- What is the difference between C and C++?
- What are the basic data types in C++?
- What is the difference between a variable and a constant?
- What is the difference between call by value and call by reference?
- What is a constructor and when is it called?
- What is the difference between inheritance and polymorphism?
- What is the difference between function overloading and function overriding?
- Why are virtual functions used in C++?
- What is the purpose of templates?
- How are exceptions handled using try, throw, and catch?
- What is the difference between a
forloop and awhileloop? - How can a C++ program read data from a text file?
Conclusion
C++ includes both basic programming concepts and advanced features. Start by learning variables, data types, operators, conditions, loops, and functions. Then move to classes, constructors, inheritance, polymorphism, templates, exceptions, and file operations.
Reading definitions is helpful, but writing and testing small programs is the best way to become comfortable with C++. Regular practice helps you understand how concepts work together.