0% found this document useful (0 votes)
25 views25 pages

Teaching Session 1

The document provides a comprehensive introduction to C++ and Object-Oriented Programming (OOP), covering its history, features, advantages, and applications. It explains key OOP concepts such as classes, objects, encapsulation, abstraction, inheritance, and polymorphism, along with code examples in C++. Additionally, it outlines the basic structure of a C++ program and offers guidance on setting up a C++ development environment.

Uploaded by

bikominr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views25 pages

Teaching Session 1

The document provides a comprehensive introduction to C++ and Object-Oriented Programming (OOP), covering its history, features, advantages, and applications. It explains key OOP concepts such as classes, objects, encapsulation, abstraction, inheritance, and polymorphism, along with code examples in C++. Additionally, it outlines the basic structure of a C++ program and offers guidance on setting up a C++ development environment.

Uploaded by

bikominr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Introduction to C++ and OOP

I-Introduction to C++: History, features, advantages and its applications

I.1 - Introduction to C++

C++ is a powerful, high-performance programming language that has been widely used in
various domains, including systems programming, game development, and applications
requiring real-time processing. Below is an overview of its history, features, advantages, and
applications.

I.2 - History of C++

• Origins: C++ was developed by Bjarne Stroustrup at Bell Labs in the early 1980s. It
was designed as an extension of the C programming language, with added support for
object-oriented programming (OOP).
• Name: Initially called "C with Classes," it was renamed to C++ in 1983. The "++"
symbolizes the incremental improvement over C.
• Standardization: The language was standardized in 1998 (C++98), with subsequent
updates in 2003 (C++03), 2011 (C++11), 2014 (C++14), 2017 (C++17), and 2020
(C++20). Each update introduced new features and improvements.

I.3 - Features of C++

1. Object-Oriented Programming (OOP):


o Supports concepts like classes, objects, inheritance, polymorphism, and
encapsulation.
o Enables modular and reusable code.
2. Procedural Programming:
o Retains the procedural programming features of C, allowing for structured
programming.
3. Standard Template Library (STL):
o Provides a rich set of template classes and functions for data structures (e.g.,
vectors, lists) and algorithms (e.g., sorting, searching).
4. Memory Management:
o Offers both manual memory management (using pointers) and automatic
memory management (using RAII - Resource Acquisition Is Initialization).
5. Portability:
o C++ code can be compiled and executed on various platforms with minimal
changes.
6. Performance:
o Known for its high performance and efficiency, making it suitable for
resource-intensive applications.
7. Multi-Paradigm:

1
o Supports multiple programming paradigms, including OOP, procedural, and
generic programming.
8. Rich Library Support:
o Comes with a vast standard library and supports third-party libraries for
additional functionality.

I.4 - Advantages of C++

1. High Performance:
o C++ is compiled directly to machine code, resulting in faster execution
compared to interpreted languages.
2. Control Over Hardware:
o Provides low-level memory manipulation, making it ideal for systems
programming and embedded systems.
3. Scalability:
o Suitable for both small-scale and large-scale applications.
4. Community and Ecosystem:
o Has a large and active community, along with extensive documentation and
resources.
5. Backward Compatibility:
o Maintains compatibility with C, allowing developers to reuse existing C code.
6. Versatility:
o Can be used for a wide range of applications, from operating systems to game
engines.

I.5 - Applications of C++

1. Systems Programming:
o Used to develop operating systems (e.g., Windows, Linux) and device drivers.
2. Game Development:
o Powers many game engines (e.g., Unreal Engine) and AAA games due to its
performance and control over hardware.
3. Embedded Systems:
o Ideal for programming microcontrollers and IoT devices.
4. Real-Time Systems:
o Used in applications requiring real-time processing, such as robotics and flight
control systems.
5. Graphics and GUI Applications:
o Used in software like Adobe Photoshop and AutoCAD for rendering and
graphical computations.
6. Web Browsers:
o Core components of browsers like Chrome and Firefox are written in C++.
7. Database Systems:
o Used in database management systems like MySQL and MongoDB.

2
8. Financial Applications:
o Employed in high-frequency trading systems due to its speed and efficiency.
9. Scientific Computing:
o Used in simulations, modeling, and other computationally intensive tasks.

I.6 - Conclusion

C++ is a versatile and powerful language that combines the efficiency of low-level
programming with the flexibility of high-level abstractions. Its rich feature set, performance,
and wide range of applications make it a popular choice for developers across industries.
Whether you're building a game, an operating system, or a real-time system, C++ provides the
tools and capabilities to get the job done efficiently.

3
II - Differences between procedural and object-oriented programming C++ with
examples of code

Procedural programming and object-oriented programming (OOP) are two different


paradigms in software development. Here's a breakdown of their differences, along with
examples in C++:

II. 1 Procedural Programming

• Focus: The program is divided into functions or procedures.


• Data and Functions: Data and functions are separate. Functions operate on data
passed to them.
• Approach: Top-down approach, where the program is divided into smaller functions.
• Reusability: Limited reusability compared to OOP.
• Example: C, Pascal, and early versions of C++.

Example in C++:

cpp
#include <iostream>
using namespace std;

// Function to add two numbers


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

// Function to subtract two numbers


int subtract(int a, int b) {
return a - b;
}

int main() {
int x = 10, y = 5;

cout << "Sum: " << add(x, y) << endl; // Output: Sum: 15
cout << "Difference: " << subtract(x, y) << endl; // Output: Difference: 5

return 0;
}
• Here, add and subtract are standalone functions that operate on data passed to them.

II. 2 Object-Oriented Programming (OOP)

• Focus: The program is divided into objects that encapsulate data and behavior.
4
• Data and Functions: Data and functions are combined into objects. Functions
(methods) operate on the object's data.
• Approach: Bottom-up approach, where the program is designed using classes and
objects.
• Reusability: High reusability through inheritance and polymorphism.
• Key Concepts: Encapsulation, Inheritance, Polymorphism, and Abstraction.
• Example: C++, Java, Python.

Example in C++:

cpp
#include <iostream>
using namespace std;

// Class definition
class Calculator {
private:
int x, y;

public:
// Constructor to initialize data
Calculator(int a, int b) : x(a), y(b) {}

// Method to add
int add() {
return x + y;
}

// Method to subtract
int subtract() {
return x - y;
}
};

int main() {
Calculator calc(10, 5); // Create an object

cout << "Sum: " << calc.add() << endl; // Output: Sum: 15
cout << "Difference: " << calc.subtract() << endl; // Output: Difference: 5

return 0;
}
• Here, Calculator is a class that encapsulates data (x and y) and methods
(add and subtract).

a) Key Differences

5
Procedural
Aspect Object-Oriented Programming
Programming

Focus Functions and procedures Objects and their interactions

Data and
Separate Combined into objects
Functions

Approach Top-down Bottom-up

High (through inheritance and


Reusability Limited
polymorphism)

Example C, Pascal C++, Java, Python

b) When to Use Which?

• Procedural Programming: Suitable for small, simple programs where performance is


critical (e.g., embedded systems).
• Object-Oriented Programming: Suitable for large, complex programs where
reusability, maintainability, and scalability are important (e.g., GUI applications, game
development).

c) Combining Both in C++

C++ supports both paradigms, allowing you to mix procedural and object-oriented
programming as needed.

6
cpp
#include <iostream>
using namespace std;

// Procedural function
void greet() {
cout << "Hello, World!" << endl;
}

// OOP class
class Greeter {
public:
void greet() {
cout << "Hello from Greeter class!" << endl;
}
};

int main() {
// Procedural approach
greet();

// OOP approach
Greeter greeter;
greeter.greet();

return 0;
}

• Output:

Hello, World!
Hello from Greeter class!

This flexibility is one of the reasons C++ is a powerful language.

7
III - Key OOP concepts: Classes, Objects, Encapsulation, Abstraction, Inheritance,
syntax with example and code C++

Object-Oriented Programming (OOP) is a programming paradigm that uses objects and


classes to structure software. Below are the key OOP concepts explained with examples in
C++:

III. 1. Classes

A class is a blueprint for creating objects. It defines properties (attributes) and behaviors
(methods) that the objects will have.

Syntax:

cpp
class ClassName {
// Access specifier
private:
// Private members (attributes/methods)
public:
// Public members (attributes/methods)
};

Example:

cpp
#include <iostream>
using namespace std;

class Car {
private:
string brand;
int year;

public:
void setBrand(string b) {
brand = b;
}

void setYear(int y) {
year = y;
}

void display() {
cout << "Brand: " << brand << ", Year: " << year << endl;
}

8
};

int main() {
Car myCar;
myCar.setBrand("Toyota");
myCar.setYear(2020);
myCar.display(); // Output: Brand: Toyota, Year: 2020
return 0;
}

III.2. Objects

An object is an instance of a class. It is created using the class blueprint.

Syntax:

cpp
Copy
ClassName objectName;

Example:

cpp
Car myCar; // myCar is an object of the Car class

III.3. Encapsulation

Encapsulation is the bundling of data (attributes) and methods that operate on the data into a
single unit (class). It also restricts direct access to some of the object's components, which is
achieved using access specifiers (private, public, protected).

Example:

cpp
class Car {
private:
string brand; // Encapsulated data

public:
void setBrand(string b) {
brand = b; // Controlled access to private data
}

string getBrand() {
return brand;
}
};

9
III.4. Abstraction

Abstraction means hiding complex implementation details and showing only the necessary
features of an object. It is achieved using classes and access specifiers.

Example:

cpp
class Car {
private:
string engineDetails; // Hidden from the user

public:
void start() {
engineDetails = "Engine started";
cout << "Car started!" << endl;
}
};

int main() {
Car myCar;
myCar.start(); // User doesn't need to know about engineDetails
return 0;
}

III.5. Inheritance

Inheritance allows a class (derived class) to inherit attributes and methods from another class
(base class). It promotes code reusability.

Syntax:

cpp
class DerivedClass : access-specifier BaseClass {
// Derived class members
};

Example:

cpp
#include <iostream>
using namespace std;

// Base class
class Vehicle {
public:

10
void honk() {
cout << "Honk honk!" << endl;
}
};

// Derived class
class Car : public Vehicle {
public:
string brand;
};

int main() {
Car myCar;
myCar.brand = "Toyota";
myCar.honk(); // Inherited from Vehicle
return 0;
}

III.6. Polymorphism

Polymorphism allows objects of different classes to be treated as objects of a common base


class. It is achieved through function overriding and virtual functions.

Example:

cpp
#include <iostream>
using namespace std;

// Base class
class Animal {
public:
virtual void sound() {
cout << "Animal sound" << endl;
}
};

// Derived class
class Dog : public Animal {
public:
void sound() override {
cout << "Woof woof!" << endl;
}
};

int main() {
Animal* myAnimal = new Dog();
myAnimal->sound(); // Output: Woof woof!
return 0;
}

11
III.7. Syntax Summary

• Class Definition:

cpp

class ClassName {
private:
// Private members
public:
// Public members
};

• Object Creation:
cpp

ClassName objectName;

• Inheritance:
cpp

class DerivedClass : access-specifier BaseClass {};

• Polymorphism:
cpp

Copy

virtual void functionName() {} // In base class


void functionName() override {} // In derived class

Summary of Key Concepts:

1. Class: Blueprint for objects.


2. Object: Instance of a class.
3. Encapsulation: Bundling data and methods, restricting access.
4. Abstraction: Hiding complex details.
5. Inheritance: Reusing code by deriving classes.
6. Polymorphism: Using a single interface for different forms.

12
IV -Basic structure and syntax of a C++ program with example flowchart

Basic Structure and Syntax of a C++ Program

A typical C++ program consists of the following components:

1. Preprocessor Directives: These are instructions to the compiler to include header


files or define constants. The most common directive is #include, which includes
standard libraries like <iostream>.
2. Main Function: Every C++ program must have a main() function, which is the entry
point of the program. Execution begins and ends here.
3. Statements and Expressions: These are the instructions that perform operations, such
as calculations, input/output, and control flow.
4. Comments: Comments are used to explain the code and are ignored by the compiler.
They can be single-line (//) or multi-line (/* ... */).
5. Return Statement: The main() function typically ends with a return 0; statement,
indicating successful execution.

Example C++ Program

cpp
#include <iostream> // Preprocessor directive to include the iostream library

int main() { // Main function


// Output to the console
std::cout << "Hello, World!" << std::endl;

return 0; // Indicates successful execution


}

Explanation of the Program

1. #include <iostream>: Includes the input/output stream library, which allows the
program to use std::cout for output.
2. int main(): The starting point of the program. The int indicates that the function
returns an integer.
3. std::cout << "Hello, World!" << std::endl;: Outputs the text "Hello, World!" to the
console. std::endl adds a newline.
4. return 0;: Indicates that the program executed successfully.

Steps in the Flowchart

1. Start: The program begins execution.


2. Include iostream: The preprocessor includes the iostream library.
3. Begin main(): The main() function starts.
4. Print "Hello, World!": The program outputs the text to the console.
5. Return 0: The program ends and returns a success status.

13
6. End: The program terminates.

This is a basic example of a C++ program and its corresponding flowchart. As programs
become more complex, the structure and flowchart will include additional components like
variables, loops, conditionals, and functions.

14
V - Setting up the C++ development environment (compiler, IDE)

Setting up a C++ development environment involves installing a compiler and choosing an


Integrated Development Environment (IDE) or a code editor. Below is a step-by-step guide to
help you set up a C++ development environment on different operating systems.

V.1. Install a C++ Compiler

A compiler is required to compile and run C++ code. The most common C++ compiler
is GCC (GNU Compiler Collection).

Windows

• MinGW (Minimalist GNU for Windows):


1. Download MinGW from MinGW Website.
2. Install it and add the bin directory to your system's PATH environment
variable.
3. Verify the installation by opening Command Prompt and typing:
bash

g++ --version

• Microsoft Visual C++ (MSVC):


o Install Visual Studio (see IDE section below), which includes the MSVC
compiler.

Linux

• Most Linux distributions come with GCC pre-installed.


• If not, install it using your package manager:
o Ubuntu/Debian:

bash

sudo apt update


sudo apt install g++

o Fedora:
bash

sudo dnf install gcc-c++

o Verify the installation:


bash

g++ --version

15
macOS

• Install Xcode Command Line Tools, which include the Clang compiler:

bash

xcode-select --install

• Verify the installation:


bash

g++ --version

V.2. Choose an IDE or Code Editor

An IDE or code editor makes writing and debugging C++ code easier.

Popular IDEs

• Visual Studio (Windows/macOS):


o Download and install Visual Studio.
o During installation, select the Desktop development with C++ workload.
o Visual Studio includes a powerful debugger and IntelliSense for code
completion.
• Code::Blocks (Windows/Linux/macOS):
o Download from Code::Blocks Website.
o It is lightweight and supports multiple compilers.
• Eclipse CDT (Windows/Linux/macOS):
o Download from Eclipse Website.
o Install the C/C++ Development Tools (CDT) plugin.
• Xcode (macOS):
o Download from the Mac App Store.
o Xcode is the official IDE for macOS development and includes the Clang
compiler.

Code Editors

• Visual Studio Code (VS Code):


1. Download and install VS Code.
2. Install the C/C++ extension from the Extensions Marketplace.
3. Configure the compiler in VS Code by editing the tasks.json file.
• Sublime Text:
o Install Sublime Text.
o Use a build system to compile and run C++ code.
• Atom:
o Install Atom.
o Use the gpp-compiler package to compile and run C++ code.

16
V.3. Write and Compile Your First C++ Program

1. Open your IDE or code editor.


2. Create a new file and save it with a .cpp extension (e.g., hello.cpp).
3. Write a simple C++ program:
cpp

#include <iostream>
using namespace std;

int main() {
cout << "Hello, World!" << endl;
return 0;
}
4. Compile and run the program:
o Using Command Line:

bash

g++ hello.cpp -o hello


./hello

o Using an IDE:
▪ Click the "Build" or "Run" button in the IDE.

4. Debugging

• Use the built-in debugger in your IDE (e.g., Visual Studio, Code::Blocks, or VS
Code).
• Set breakpoints, inspect variables, and step through your code.

5. Additional Tools

• CMake: For managing build processes.


• Git: For version control.
• Doxygen: For generating documentation.

17
VI. Input/output operations in C++ (cin, cout) with examples of code

Input and output operations in C++ are primarily handled using the cin and cout objects,
which are part of the iostream library. cin is used for input operations, while cout is used for
output operations. Below are examples and explanations of how to use these in C++.

VI.1. Output with cout

cout is used to display output to the standard output device (usually the screen). It is used with
the insertion operator <<.

Example:

cpp
#include <iostream>
using namespace std;

int main() {
cout << "Hello, World!" << endl; // Outputs "Hello, World!" followed by a newline
cout << "C++ is fun!"; // Outputs "C++ is fun!"
return 0;
}

Output:

Hello, World!
C++ is fun!
• << is the insertion operator, used to insert data into the output stream.
• endl is used to insert a newline character and flush the output buffer.

VI.2. Input with cin

cin is used to read input from the standard input device (usually the keyboard). It is used with
the extraction operator >>.

Example:

cpp
#include <iostream>
using namespace std;

int main() {
int age;
cout << "Enter your age: "; // Prompt the user
cin >> age; // Read input into the variable 'age'
cout << "You are " << age << " years old." << endl;

18
return 0;
}

Output (if user enters 25):

Enter your age: 25


You are 25 years old.
• >> is the extraction operator, used to extract data from the input stream.
• The input is stored in the variable age.

VI.3. Combining Input and Output

You can combine cin and cout to create interactive programs.

Example:

cpp
#include <iostream>
using namespace std;

int main() {
string name;
int age;

cout << "Enter your name: ";


cin >> name; // Read a string (stops at whitespace)
cout << "Enter your age: ";
cin >> age; // Read an integer

cout << "Hello, " << name << "! You are " << age << " years old." << endl;
return 0;
}

Output (if user enters Alice and 30):

Enter your name: Alice


Enter your age: 30
Hello, Alice! You are 30 years old.

VI.4. Handling Multiple Inputs

You can use cin to read multiple inputs in a single statement.

Example:

19
cpp
#include <iostream>
using namespace std;

int main() {
int num1, num2;
cout << "Enter two numbers: ";
cin >> num1 >> num2; // Read two integers
cout << "You entered: " << num1 << " and " << num2 << endl;
return 0;
}

Output (if user enters 10 and 20):

Enter two numbers: 10 20


You entered: 10 and 20

VI.5. Handling Strings with getline

cin stops reading input at the first whitespace character. To read an entire line of input
(including spaces), use getline.

Example:

cpp
#include <iostream>
using namespace std;

int main() {
string fullName;
cout << "Enter your full name: ";
cin.ignore(); // Ignore any leftover newline character in the buffer
getline(cin, fullName); // Read the entire line
cout << "Hello, " << fullName << "!" << endl;
return 0;
}

Output (if user enters John Doe):

Enter your full name: John Doe


Hello, John Doe!

VI.6. Error Handling with Input

You can check if the input operation was successful using the cin.fail() method.

20
Example:

cpp
#include <iostream>
using namespace std;

int main() {
int number;
cout << "Enter a number: ";
cin >> number;

if (cin.fail()) {
cout << "Invalid input! Please enter a number." << endl;
} else {
cout << "You entered: " << number << endl;
}
return 0;
}

Output (if user enters abc):

Enter a number: abc


Invalid input! Please enter a number.

Summary

• Use cout with << for output.


• Use cin with >> for input.
• Use getline to read entire lines of text.
• Always handle potential input errors for robust programs.

These are the basics of input/output operations in C++! Let me know if you need further
clarification or examples.

21
VII. Data types, operators, and control structures in c++ with examples for each case

C++ is a powerful programming language that supports various data types, operators, and
control structures. Below is an explanation of each with examples:

VII.1. Data Types in C++

Data types define the type of data a variable can hold. C++ supports the following basic data
types:

a. Fundamental Data Types

• int: Integer type (e.g., int age = 25;)


• float: Single-precision floating-point (e.g., float pi = 3.14;)
• double: Double-precision floating-point (e.g., double distance = 123.456;)
• char: Single character (e.g., char grade = 'A';)
• bool: Boolean (true/false) (e.g., bool isActive = true;)

b. Derived Data Types

• Array: Collection of similar data types (e.g., int numbers[5] = {1, 2, 3, 4, 5};)
• Pointer: Stores memory address (e.g., int* ptr = &age;)
• Reference: Alias for a variable (e.g., int& ref = age;)

c. User-Defined Data Types

• struct: Group of variables (e.g., struct Person { string name; int age; };)
• class: Blueprint for objects (e.g., class Car { public: string model; int year; };)
• enum: Enumerated type (e.g., enum Color { RED, GREEN, BLUE };)

VII.2. Operators in C++

Operators are symbols that perform operations on variables and values.

a. Arithmetic Operators

• + (Addition): int sum = a + b;


• - (Subtraction): int diff = a - b;
• * (Multiplication): int product = a * b;
• / (Division): float quotient = a / b;
• % (Modulus): int remainder = a % b;

b. Relational Operators

• == (Equal to): if (a == b) { ... }


• != (Not equal to): if (a != b) { ... }
• > (Greater than): if (a > b) { ... }

22
• < (Less than): if (a < b) { ... }
• >= (Greater than or equal to): if (a >= b) { ... }
• <= (Less than or equal to): if (a <= b) { ... }

c. Logical Operators

• && (Logical AND): if (a > 0 && b > 0) { ... }


• || (Logical OR): if (a > 0 || b > 0) { ... }
• ! (Logical NOT): if (!isActive) { ... }

d. Assignment Operators

• = (Assign): int x = 10;


• += (Add and assign): x += 5; // x = x + 5
• -= (Subtract and assign): x -= 3; // x = x - 3
• *= (Multiply and assign): x *= 2; // x = x * 2
• /= (Divide and assign): x /= 2; // x = x / 2

e. Increment/Decrement Operators

• ++ (Increment): x++; // x = x + 1
• -- (Decrement): x--; // x = x - 1

f. Ternary Operator

• ? : (Conditional operator): int max = (a > b) ? a : b;

VII.3. Control Structures in C++

Control structures determine the flow of execution in a program.

a. Decision-Making Structures

• if statement:

cpp

if (a > b) {
cout << "a is greater than b";
}

• if-else statement:
cpp

if (a > b) {
cout << "a is greater than b";
} else {
cout << "b is greater than or equal to a";
}

• switch statement:

23
cpp

switch (grade) {
case 'A': cout << "Excellent"; break;
case 'B': cout << "Good"; break;
default: cout << "Invalid grade";
}

b. Looping Structures

• for loop:

cpp

for (int i = 0; i < 5; i++) {


cout << i << " ";
}

• while loop:
cpp

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

• do-while loop:
cpp

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

c. Jump Statements
• break: Exits a loop or switch statement.

cpp

for (int i = 0; i < 10; i++) {


if (i == 5) break;
cout << i << " ";
}
• continue: Skips the current iteration of a loop.
cpp

for (int i = 0; i < 10; i++) {


if (i == 5) continue;

24
cout << i << " ";
}

• return: Exits a function and optionally returns a value.


cpp

int add(int a, int b) {


return a + b;
}

Example Program Combining All Concepts

cpp
#include <iostream>
using namespace std;

int main() {
// Data types
int a = 10, b = 20;
float pi = 3.14;
char grade = 'A';
bool isActive = true;

// Operators
int sum = a + b;
bool isGreater = (a > b);

// Control structures
if (isGreater) {
cout << "a is greater than b" << endl;
} else {
cout << "b is greater than or equal to a" << endl;
}

for (int i = 0; i < 5; i++) {


cout << i << " ";
}

return 0;
}

This program demonstrates the use of data types, operators, and control structures in C++. Let
me know if you need further clarification!

25

You might also like