C++ Programming: Concepts, Examples and Object-Oriented Programming

A practical guide to learning the basics of C++, programming concepts, functions, classes and object-oriented programming.

Introduction to C++

C++ is a general-purpose programming language that is widely used for software development, system programming, game development and competitive programming. It was developed by Bjarne Stroustrup as an extension of the C programming language.

One reason C++ is still important in Computer Science is that it gives programmers a high level of control over memory and system resources while also providing features such as classes, inheritance and polymorphism. Learning C++ also provides a strong foundation for understanding data structures and other programming languages.

In this guide, we will cover the basic syntax of C++, data types, operators, control statements, functions and the major concepts of object-oriented programming.

Important Characteristics of C++

  • General-purpose: C++ can be used to build many different types of applications.
  • Compiled language: C++ source code is normally compiled into machine code before the resulting program is executed.
  • Object-oriented: C++ supports classes, objects, inheritance, polymorphism and other object-oriented programming concepts.
  • Portable: C++ source code can generally be compiled on different operating systems, although platform-specific code and libraries may require changes.
  • High performance: C++ provides low-level control and is commonly used where performance and efficient resource usage are important.

Your First C++ Program

A simple C++ program can be used to understand the basic structure of the language. The following program displays a message on the screen.

#include <iostream>
using namespace std;

int main() {
    cout << "Hello, World!";
    return 0;
}

Understanding the Program

  • #include <iostream> includes the standard input and output stream library.
  • main() is the function where execution of a C++ program begins.
  • cout is used to display output on the screen.
  • << is the stream insertion operator used with cout.
  • return 0; indicates that the program completed successfully.

C++ Tokens

A token is one of the smallest meaningful elements of a C++ program. The compiler uses these elements to understand the structure of the code.

Common types of tokens include:

  • Keywords: Reserved words such as int, class, if and return.
  • Identifiers: Names given to variables, functions, classes and other program elements.
  • Constants: Values that do not change during a particular operation or program execution.
  • Operators: Symbols used to perform operations such as addition, comparison and logical operations.
  • String literals: Text written inside double quotation marks.

C++ Data Types

A data type tells the compiler what kind of value a variable is expected to store. Choosing an appropriate data type helps a program work with data correctly and efficiently.

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;

C++ also provides other types such as arrays, pointers, references, structures and classes for handling more complex data.

Variables and Constants

A variable is a named memory location used to store a value that may change during program execution.

int marks = 85;
cout << marks;

In this example, marks stores the value 85. The value can be changed later in the program.

Constants

A constant is a value that should not be changed after it has been initialized.

const double PI = 3.14159;

C++ Operators

Operators are symbols used to perform operations on values and variables. C++ provides several categories of operators.

Common Types of Operators

  • Arithmetic: +, -, *, /, %
  • Relational: ==, !=, >, <, >=, <=
  • Logical: &&, ||, !
  • Assignment: =, +=, -=, *=, /=
  • Increment and decrement: ++, --
  • Bitwise: &, |, ^, ~, <<, >>
  • Conditional: ?:

Example of Arithmetic Operators

Suppose a = 10 and b = 5.

Operator Expression Result
+ a + b 15
- a - b 5
* a * b 50
/ a / b 2
% a % b 0

Control Structures in C++

Control statements determine which parts of a program should execute and how many times a particular block of code should run.

1. if-else Statement

The if statement is used when a program needs to make a decision based on a condition.

int marks = 75;

if (marks >= 40) {
    cout << "Pass";
}
else {
    cout << "Fail";
}

If the condition marks >= 40 is true, the program displays "Pass"; otherwise it displays "Fail".

2. for Loop

A for loop is useful when the number of repetitions is known or can be controlled using a counter.

for (int i = 1; i <= 5; i++) {
    cout << i << " ";
}

The program prints the numbers from 1 to 5.

3. while Loop

A while loop repeats a block of code as long as its condition remains true.

int i = 1;

while (i <= 5) {
    cout << i << " ";
    i++;
}

4. switch Statement

A switch statement is useful when one value needs to be compared with several possible cases.

int choice = 2;

switch (choice) {
    case 1:
        cout << "Add";
        break;

    case 2:
        cout << "Edit";
        break;

    default:
        cout << "Invalid choice";
}

Functions in C++

A function is a block of code designed to perform a particular task. Functions make programs easier to organize because a task can be written once and called whenever it is needed.

Simple Function Example

int add(int a, int b) {
    return a + b;
}

int main() {

    int result = add(10, 20);

    cout << result;

    return 0;
}

Here, the add() function receives two numbers and returns their sum.

Call by Value

In call by value, a copy of the argument is passed to the function. Changing the parameter inside the function does not change the original variable.

void change(int x) {
    x = 100;
}

int main() {

    int a = 10;

    change(a);

    cout << a;   // Output: 10

    return 0;
}

Call by Reference

In call by reference, the function receives a reference to the original variable. Changes made through the reference affect the original variable.

void change(int &x) {
    x = 100;
}

int main() {

    int a = 10;

    change(a);

    cout << a;   // Output: 100

    return 0;
}

Object-Oriented Programming in C++

C++ supports object-oriented programming, where programs can be organized around objects that contain data and functions.

The four commonly discussed principles of object-oriented programming are encapsulation, abstraction, inheritance and polymorphism.

1. Encapsulation

Encapsulation means keeping related data and functions together and controlling how the data is accessed.

For example, in a bank account class, the account balance should not normally be changed directly from outside the class. Methods such as deposit() and withdraw() can control how the balance is modified.

2. Abstraction

Abstraction means showing the important features of an object while hiding unnecessary implementation details.

For example, when you use a car, you can use the steering wheel and pedals without needing to know every internal detail of the engine.

3. Inheritance

Inheritance allows a new class to reuse and extend features of an existing class.

class Animal {
public:

    void eat() {
        cout << "Eating";
    }
};

class Dog : public Animal {
public:

    void bark() {
        cout << "Barking";
    }
};

Here, Dog derives from Animal. The Dog class can use the accessible members inherited from Animal in addition to its own members.

4. Polymorphism

Polymorphism means "many forms". In C++, the same function name or interface can produce different behaviour depending on how it is used. Common examples include function overloading and function overriding.

Classes and Objects

A class is a user-defined type that groups data and functions together. An object is an instance of a class.

class Student {

public:

    string name;
    int marks;

    void display() {
        cout << name << " " << marks;
    }
};

int main() {

    Student student;

    student.name = "Rahul";
    student.marks = 85;

    student.display();

    return 0;
}

In this example, Student is the class and student is an object created from that class.

Constructors

A constructor is a special member function that is automatically called when an object is created. It is commonly used to initialize the data members of a class.

Default Constructor

class Rectangle {

private:
    int length;
    int width;

public:

    Rectangle() : length(0), width(0) {
    }
};

Parameterized Constructor

class Rectangle {

private:
    int length;
    int width;

public:

    Rectangle(int l, int w)
        : length(l), width(w) {
    }
};

Copy Constructor

A copy constructor creates an object using another object of the same class.

class Rectangle {

private:
    int length;
    int width;

public:

    Rectangle(int l, int w)
        : length(l), width(w) {
    }

    Rectangle(const Rectangle &obj)
        : length(obj.length),
          width(obj.width) {
    }

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

Function Overloading

Function overloading allows multiple functions to have the same name as long as their parameter lists are different.

int add(int a, int b) {
    return a + b;
}

double add(double a, double b) {
    return a + b;
}

The compiler determines which function should be called based on the arguments supplied.

Runtime Polymorphism

Runtime polymorphism is commonly implemented using virtual functions. A base-class pointer or reference can refer to an object of a derived class, and the overridden function can be selected at runtime.

class Animal {

public:

    virtual void sound() {
        cout << "Animal sound";
    }
};

class Dog : public Animal {

public:

    void sound() override {
        cout << "Dog barks";
    }
};

int main() {

    Animal* animal = new Dog();

    animal->sound();

    delete animal;

    return 0;
}

Because sound() is virtual, the Dog implementation is called even though the pointer type is Animal.

Templates in C++

Templates support generic programming. They allow the same logic to be used with different data types instead of writing separate versions of a function for every type.

Function Template Example

template <typename T>
T maximum(T a, T b) {

    return (a > b) ? a : b;
}

int main() {

    cout << maximum(10, 20);

    return 0;
}

The function can work with different compatible types because T acts as a placeholder for the actual type.

Exception Handling

Exception handling provides a way to detect and handle exceptional situations while a program is running. C++ commonly uses try, throw and catch for this purpose.

#include <iostream>
#include <stdexcept>

using namespace std;

int main() {

    int numerator = 10;
    int denominator = 0;

    try {

        if (denominator == 0) {
            throw runtime_error("Division by zero");
        }

        cout << numerator / denominator;
    }

    catch (const runtime_error &e) {

        cout << "Error: " << e.what();
    }

    return 0;
}
  • try contains code that may generate an exception.
  • throw reports an exceptional condition.
  • catch handles the exception.

File Handling in C++

C++ provides file stream classes for reading data from files and writing data to files. The commonly used classes are ofstream, ifstream and fstream.

Writing to a File

#include <fstream>

using namespace std;

int main() {

    ofstream outFile("example.txt");

    if (!outFile) {
        return 1;
    }

    outFile << "Hello from C++";

    outFile.close();

    return 0;
}

Reading from a File

#include <fstream>
#include <iostream>

using namespace std;

int main() {

    ifstream inFile("example.txt");

    if (!inFile) {
        cout << "Unable to open file.";
        return 1;
    }

    string text;

    getline(inFile, text);

    cout << text;

    inFile.close();

    return 0;
}

Checking whether a file opened successfully is important because the file may not exist, may be inaccessible, or may be located at a different path.

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 used to initialize an object.
  • Inheritance: A mechanism through which one class can derive features from another class.
  • Polymorphism: The ability to use a common interface with different implementations.
  • Encapsulation: Keeping data and related functions together while controlling access.
  • Abstraction: Hiding unnecessary implementation details and exposing the important functionality.
  • Template: A feature that allows generic code to work with different data types.
  • Exception: An unusual condition that can be handled using C++ exception-handling mechanisms.

C++ Programming Practice Questions

Reading programming concepts is only the first step. Try solving small problems after studying each topic. This helps you check whether you can apply the concept instead of only remembering its definition.

  1. What is the difference between C and C++?
  2. What are the basic data types available in C++?
  3. What is the difference between a variable and a constant?
  4. What is the difference between call by value and call by reference?
  5. What is a constructor and when is it called?
  6. What is the difference between inheritance and polymorphism?
  7. What is the difference between function overloading and overriding?
  8. Why are virtual functions used in C++?
  9. What is the purpose of templates?
  10. How are exceptions handled using try, throw and catch?
  11. What is the difference between a for loop and a while loop?
  12. How can a C++ program read data from a text file?

Conclusion

C++ has a wide range of features, starting from basic variables and control statements and extending to object-oriented programming, templates, exception handling and file operations. It can look difficult when all of these topics are studied together, but learning them one concept at a time makes the language easier to understand.

If you are preparing for a Computer Science examination, first become comfortable with basic syntax, data types, operators, loops and functions. After that, spend more time on classes, constructors, inheritance and polymorphism. Finally, practice small programs rather than only reading definitions.

Regular practice is the best way to become comfortable with C++. Start with simple programs and gradually move to problems that combine multiple concepts.