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.
Learn the fundamentals of C++, including syntax, variables, control statements, functions, classes, inheritance, polymorphism, templates, exceptions, and file handling.
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.
The following program displays a message on the screen:
#include <iostream>
int main() {
std::cout << "Hello, World!
";
return 0;
}
#include <iostream> provides input and output stream facilities.main() is the function where a C++ program begins execution.std::cout displays output on the screen.<< is the stream insertion operator.return 0; indicates successful program completion. In main(), 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.
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.
int, class, if, and return.10, 3.14, 'A', and "Hello".+, ==, and &&.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"; |
A variable is a named storage location whose value can change during program execution.
int marks = 85;
marks = 90;
A constant is a value that should not change after it is initialised.
const double pi = 3.14159;
Operators are symbols used to perform operations on values and variables.
+, -, *, /, %==, !=, >, <, >=, <=&&, ||, !=, +=, -=, *=, /=++, --&, |, ^, ~, <<, >>?: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.
Control statements determine which part of a program executes and how often a block of code repeats.
#include <iostream>
int main() {
int marks = 75;
if (marks >= 40) {
std::cout << "Pass
";
} else {
std::cout << "Fail
";
}
}
#include <iostream>
int main() {
for (int i = 1; i <= 5; ++i) {
std::cout << i << " ";
}
}
#include <iostream>
int main() {
int i = 1;
while (i <= 5) {
std::cout << i << " ";
++i;
}
}
#include <iostream>
int main() {
int choice = 2;
switch (choice) {
case 1:
std::cout << "Add
";
break;
case 2:
std::cout << "Edit
";
break;
default:
std::cout << "Invalid choice
";
}
}
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 << "
";
}
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 << "
"; // Output: 10
}
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 << "
"; // Output: 100
}
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 << "
";
}
};
int main() {
Student student;
student.name = "Rahul";
student.marks = 85;
student.display();
}
In this example, Student is the class and student is an object.
C++ supports object-oriented programming. The following four principles are commonly taught as the main OOP concepts.
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 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 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
";
}
};
class Dog : public Animal {
public:
void bark() const {
std::cout << "Barking
";
}
};
int main() {
Dog dog;
dog.eat();
dog.bark();
}
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.
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;
}
};
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;
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 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
";
}
};
class Dog : public Animal {
public:
void sound() const override {
std::cout << "Dog barks
";
}
};
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.
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) << "
";
std::cout << maximum(2.5, 3.7) << "
";
}
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 << "
";
} catch (const std::runtime_error& error) {
std::cout << "Error: " << error.what() << "
";
}
}
try contains code that may cause an exception.throw reports an exceptional condition.catch handles the exception.
C++ uses file streams to read from and write to files. The main file stream classes are
std::ofstream, std::ifstream, and std::fstream.
#include <fstream>
int main() {
std::ofstream outputFile("example.txt");
if (!outputFile) {
return 1;
}
outputFile << "Hello from C++
";
}
#include <fstream>
#include <iostream>
#include <string>
int main() {
std::ifstream inputFile("example.txt");
if (!inputFile) {
std::cout << "Unable to open file.
";
return 1;
}
std::string text;
std::getline(inputFile, text);
std::cout << text << "
";
}
Always check whether a file opened successfully. A file may be missing, inaccessible, or located at a different path.
for loop and a while loop?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.
Correct Answer: B) Virtual Functions
Explanation: Virtual functions enable runtime polymorphism in C++. When a base class pointer points to a derived object, calling a virtual function executes the derived class's overridden version at runtime.
Correct Answer: B) 3
Explanation: When both operands in a division operation are integers in C++, integer division removes the fractional part, yielding 3.
Correct Answer: C) ->
Explanation: The arrow operator (->) is used to access members of a class or struct through an object pointer in C++.
Correct Answer: A) Encapsulation
Explanation: Encapsulation bundles data and functions together while controlling external access to internal state using private data members and public methods.
Correct Answer: A) try, catch, and throw
Explanation: C++ exception handling uses try blocks to enclose code that may throw exceptions, throw to report errors, and catch blocks to handle them.
These primary standards, official documentation, and established textbooks are useful for checking terminology and studying beyond this revision guide.