(Ch6) Computer Programming
(Ch6) Computer Programming
Problem Modeling Difficult for real-world problems Intuitive for real-world problems
Historical Background
Impact of C++
1.Header Files:
○ Libraries included at the top of the program using #include.
○ Example: #include<iostream> for input/output operations.
2.Namespace Declaration:
○ Allows grouping of identifiers under a unique name to avoid
conflicts.
○ Example: using namespace std;
3.Global Variables and Function Declarations:
○ Variables and functions declared outside main() that are
accessible throughout the program.
4.main() Function:
○ Entry point of the program where execution begins.
○ Every C++ program must have one main() function.
5.User-Defined Functions and Classes:
○ Functions or classes defined by the programmer to
modularize code.
6.Comments:
○ Used for documentation and ignored by the compiler.
■ Single-line: //.
■ Multi-line: /* */.
Example:
// Function prototype
void display();
int main() {
return 0;
void display() {
}
Key Components:
Overview
Common Streams:
Input/Output Operations
int age;
cout << "Enter your age: ";
cin >> age;
3.endl:
○ Inserts a newline and flushes the output buffer.
4.Formatted I/O:
○ Input and output can be formatted using manipulators (from
<iomanip>).
○ Example:
#include<iomanip>
cout << fixed << setprecision(2) << 123.456; // Output: 123.46
Example Program:
#include<iostream>
int main() {
int num;
double salary;
cout << "You entered integer: " << num << endl;
cout << "Your salary is: " << salary << endl;
return 0;
}
Output:
Enter an integer: 25
Key Points:
Definition
Core Concepts
1.Objects:
○ An object is an instance of a class.
○ It contains data (attributes) and methods (functions).
○ Example: A "Car" object may have attributes like color and
brand, and methods like drive() and stop().
2.Classes:
○ A class is a blueprint for creating objects.
○ It defines the properties and behaviors that objects of the
class will have.
3.Encapsulation:
○ Encapsulation binds together the data and the functions
that manipulate the data.
○ Example: An object hides its internal state and requires
interaction through methods.
4.Abstraction:
○ Focuses on hiding the implementation details and showing
only the essential features of an object.
5.Inheritance:
○ Allows one class to inherit properties and behavior from
another class, promoting code reuse.
6.Polymorphism:
○ Enables objects to take on multiple forms, allowing
methods to be used in different ways based on the context.
Advantages of OOP
1.Banking System:
○ Classes: Account, Customer, Transaction
○ Objects: Individual customer accounts, specific
transactions
2.E-commerce Platform:
○ Classes: Product, Order, Customer
○ Objects: Individual products, customer orders
3.Game Development:
○ Classes: Player, Enemy, Weapon
○ Objects: Specific characters, weapons
History of OOP
● Same as C.
● Different in C++:
1.C++ allows variables to be declared anywhere in the
program (e.g., inside loops), unlike C, which requires
declaration at the beginning of a block.
2.C++ introduces references (int &ref = var;) as part of
variable declaration.
3.C++ supports object-oriented variable initialization using
constructors.
Statements:
● Same as C.
Data Types:
● Different in C++:
1.C++ introduces additional data types like bool, string, and
wchar_t.
2.bool type is used to store true or false values (not present
in C).
3.The string class in C++ simplifies string manipulation
compared to C's character arrays.
Type Conversion:
● Different in C++:
1.C++ introduces explicit type casting for safer conversions
(e.g., static_cast, dynamic_cast, const_cast, and
reinterpret_cast), unlike C's traditional type casting.
2.Implicit conversions still work similarly in both languages.
Preprocessor Directives:
● Same as C.
Namespace:
● Different in C++:
1.Introduced in C++ to group identifiers and avoid naming
conflicts (e.g., std namespace for standard libraries).
2.Syntax: using namespace std; or explicit std::cout.
● Different in C++:
1.C++ replaces malloc and free with new and delete, which
also call constructors and destructors for objects.
Syntax:
int *ptr = new int; // Allocate memory
● Same as C.
Functions:
● Different in C++:
1.C++ supports function overloading (multiple functions with
the same name but different parameter types).
2.Inline functions are introduced using the inline keyword for
efficiency.
3.Member functions are used within classes.
Default Argument:
● Different in C++:
1.Introduced in C++ to provide default values for function
parameters.
Example:
void greet(string name = \"Guest\") {
● Different in C++:
1.C++ introduces references (int &ref) to pass and return
variables by reference without pointers.
Example:
void increment(int &x) {
x++;
● Different in C++:
1.C++ introduces the std::string class for string manipulation,
simplifying usage compared to C's char arrays.
2.std::array and std::vector are also available as part of the
C++ Standard Template Library (STL).
Structure and Union:
● Different in C++:
1.Structures in C++ can have member functions,
constructors, destructors, and access modifiers
(public/private).
Example:
struct Employee {
string name;
int age;
};
● Different in C++:
1.C++ introduces enum class for type-safe enumerations to
avoid implicit conversions to integers.
Example:
enum class Color { RED, GREEN, BLUE };
Color c = Color::RED;
Objects
Classes
class ClassName {
public:
int attribute1;
float attribute2;
// Method body
};
// Define a class
class Car {
public:
// Attributes
string brand;
string color;
int speed;
void displayDetails() {
cout << "Speed: " << speed << " km/h" << endl;
speed += increment;
cout << "Car accelerated to " << speed << " km/h." << endl;
}
};
int main() {
Car myCar;
// Set attributes
myCar.brand = "Tesla";
myCar.color = "Red";
myCar.speed = 100;
// Call methods
myCar.displayDetails();
myCar.accelerate(50);
return 0;
Explanation of Example
1.Class Definition:
○ Car is defined with three attributes (brand, color, speed)
and two methods (displayDetails() and accelerate()).
2.Object Creation:
○ myCar is an instance of the class Car.
3.Attribute Assignment:
○ Attributes are assigned values using the dot operator (.).
4.Method Invocation:
○ Methods are called using the dot operator to perform
actions like displaying car details and accelerating the car.
Output:
Brand: Tesla
Color: Red
1. Abstraction
● Definition:
○ Abstraction focuses on showing only the essential features
of an object while hiding the implementation details.
○ It simplifies complex systems by reducing unnecessary
details.
● Implementation in C++:
○ Achieved through classes and access modifiers (public,
private, protected).
○ Only the required information is exposed to the user.
Example:
#include<iostream>
class Calculator {
public:
private:
void internalLogic() {
}};
int main() {
Calculator calc;
calc.add(10, 5);
calc.subtract(10, 5);
return 0;
Output:
Sum: 15
Difference: 5
2. Encapsulation
● Definition:
○ Encapsulation binds together the data and the methods
that operate on the data into a single unit (class).
○ It restricts direct access to some of the object's
components, maintaining data security.
● Implementation in C++:
○ Achieved using access modifiers (public, private,
protected).
○ Public: Accessible from anywhere.
○ Private: Accessible only within the class.
○ Protected: Accessible within the class and derived
classes.
Example:
#include<iostream>
class Account {
private:
int balance;
public:
void setBalance(int b) {
balance = b;
int getBalance() {
return balance;
};
int main() {
Account acc;
acc.setBalance(1000);
return 0;
Output:
● Definition:
○ Inheritance allows one class to acquire the properties and
behaviors of another class.
○ The class that inherits is called the derived class, and the
class being inherited is the base class.
● Types of Inheritance in C++:
○ Single, Multiple, Multilevel, Hierarchical, and Hybrid.
Example:
#include<iostream>
class Animal {
public:
void eat() {
};
public:
void bark() {
};
int main() {
Dog dog;
return 0;
Output:
Type Effect
● Definition:
○ Polymorphism means "many forms" and allows methods to
perform differently based on the context.
○ Types in C++:
■ Compile-time Polymorphism: Achieved using
function overloading and operator overloading.
■ Run-time Polymorphism: Achieved using virtual
functions.
class Math {
public:
return a + b;
return a + b;
}};
int main() {
Math math;
cout << "Sum (int): " << math.add(10, 20) << endl;
cout << "Sum (double): " << math.add(10.5, 20.5) << endl;
return 0;
}
Output:
Sum (int): 30
class Shape {
public:
};
public:
};
int main() {
Shape *shape;
Circle circle;
shape = &circle;
return 0;
1. Constructors
- Definition:
- A constructor is a special member function of a class that is
automatically called when an object of the class is created.
- Used to initialize objects.
- Key Characteristics:
1.Has the same name as the class.
2.Does not have a return type, not even void.
3.Can be overloaded to create multiple types of constructors.
Types of Constructors
1. Default Constructor
2. Parameterized Constructor
- Definition: A constructor that takes arguments to initialize an
object with specific values.
- Purpose: Provides flexibility to set initial values for objects.
Example:
#include<iostream>
using namespace std;
class Person {
public:
string name;
int age;
// Parameterized Constructor
Person(string n, int a) {
name = n;
age = a;
}
void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}};
int main() {
Person p("John", 25); // Parameterized constructor is called
p.display();
return 0;
}
Output:
Name: John, Age: 25
2. Destructors
- Definition:
- A destructor is a special member function of a class that is
automatically called when an object goes out of scope or is
explicitly deleted.
- Used to release resources (e.g., memory, file handles).
- Key Characteristics:
1.Has the same name as the class but is preceded by a tilde
(~).
2.Cannot be overloaded (only one destructor per class).
3.Does not take arguments and has no return type.
Example:
#include<iostream>
using namespace std;
class Person {
public:
string name;
// Constructor
Person(string n) {
name = n;
cout << name << " created." << endl;
}
// Destructor
~Person() {
cout << name << " destroyed." << endl;
}};
void main() {
Person p("Alice"); // Constructor is called
}
Output:
Alice created.
Alice destroyed.