0% found this document useful (0 votes)
8 views

(Ch6) Computer Programming

This document provides an introduction to C++, covering key concepts such as procedure-oriented vs object-oriented programming, the origin and features of C++, and the structure of C++ programs. It outlines the principles of object-oriented programming, including encapsulation, inheritance, and polymorphism, while also detailing input/output operations and the use of classes and objects. Additionally, it highlights the advantages of C++ over C, including enhanced data types, dynamic memory allocation, and improved code organization.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

(Ch6) Computer Programming

This document provides an introduction to C++, covering key concepts such as procedure-oriented vs object-oriented programming, the origin and features of C++, and the structure of C++ programs. It outlines the principles of object-oriented programming, including encapsulation, inheritance, and polymorphism, while also detailing input/output operations and the use of classes and objects. Additionally, it highlights the advantages of C++ over C, including enhanced data types, dynamic memory allocation, and improved code organization.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Unit VI: Introduction to C++ (6 hrs)​

6.1 Procedure-oriented vs object-oriented


programming​
6.2 Concepts of object-oriented programming
(object, class, abstraction, encapsulation,
inheritance and polymorphism)​
6.3 Origin of C++​
6.4 Features of C++​
6.5 C++ program structure​
6.6 Input/output streams​
6.7 Access specifiers​
6.8 Objects and accessing data members and
member functions​
6.9 Constructors (default and parameterized) and
destructors
Procedure-Oriented vs Object-Oriented Programming

Procedure-Oriented Programming (POP)

●​ Definition: Focuses on procedures (functions) and step-by-step


instructions to solve problems.
●​ Key Characteristics:
○​ Programs are divided into functions.
○​ Emphasis on functions rather than data.
○​ Data is generally global and shared among functions.
○​ Does not provide strict control over data (no
encapsulation).
○​ Difficult to model real-world problems directly.
●​ Advantages:
○​ Simple to understand for small programs.
○​ Easy to debug and test smaller units (functions).
○​ Efficient for straightforward computational tasks.
●​ Disadvantages:
○​ Poor scalability for large projects.
○​ Lack of data security as global data can be accessed and
modified freely.
○​ Harder to reuse code across projects.
Object-Oriented Programming (OOP)

●​ Definition: Focuses on objects that encapsulate data and the


methods that operate on that data.
●​ Key Characteristics:
○​ Programs are divided into classes and objects.
○​ Emphasis on data rather than functions.
○​ Provides encapsulation (data hiding).
○​ Implements principles like inheritance, polymorphism, and
abstraction.
○​ Models real-world problems effectively.
●​ Advantages:
○​ Code reusability via inheritance.
○​ Better data security through encapsulation.
○​ Easy to scale and maintain large projects.
○​ Improved problem-solving for complex systems.
●​ Disadvantages:
○​ Increased complexity for small projects.
○​ Higher learning curve.
○​ Slower execution compared to POP for simple tasks.
Key Differences

Aspect Procedure-Oriented Object-Oriented

Focus Functions/Procedures Objects and Classes

Data Global and shared among functions Encapsulated within objects

Code Reusability Limited High (via inheritance)

Problem Modeling Difficult for real-world problems Intuitive for real-world problems

Scalability Poor for large projects Good for large projects


Origin of C++

Historical Background

●​ Inventor: Bjarne Stroustrup.


●​ Development: Started in 1979 at Bell Labs, USA.
●​ Motivation:
○​ Combine the power and efficiency of C with higher-level
programming concepts.
○​ Add features to improve problem-solving for complex
systems.
●​ Original Name: Initially called "C with Classes."
○​ The "class" concept was introduced to support
object-oriented programming.
●​ Renamed: Became "C++" in 1983.
○​ "++" symbolizes the increment operator, indicating an
enhancement over C.

Impact of C++

●​ Revolutionized software development by introducing


object-oriented programming to a widely-used language.
●​ Became a foundation for modern programming languages like
Java, C#, and Python.
●​ Widely adopted for system programming, game development,
and real-time applications.
C++ Program Structure

General Structure of a C++ Program

A C++ program consists of the following components:

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:

#include<iostream> // Header file

using namespace std; // Namespace declaration

// Global variable declaration

int globalVar = 10;

// Function prototype

void display();

int main() {

int localVar = 5; // Local variable

cout << "Hello, World!" << endl; // Output statement

cout << "Global Variable: " << globalVar << endl;

display(); // Function call

return 0;

void display() {

cout << "This is a user-defined function." << endl;

}
Key Components:

●​ Header Files: Provide access to standard libraries.


●​ Namespace: Simplifies code by avoiding prefixing library
functions.
●​ main(): Controls the flow of the program.
●​ User-Defined Functions: Break the program into modular
components.
●​ Variables: Used to store data, with scope defined by their
placement.
Input/Output Streams in C++

Overview

●​ C++ uses streams to perform input and output operations.


●​ A stream is a sequence of bytes flowing from a source to a
destination.

Common Streams:

1.​Input Stream: Used for input operations (e.g., keyboard).


○​ cin: Standard input stream.
2.​Output Stream: Used for output operations (e.g., console).
○​ cout: Standard output stream.

Input/Output Operations

1.​cin (Input Stream):


○​ Reads input from the keyboard.
○​ Syntax: cin >> variable;
○​ Example:

int age;​
cout << "Enter your age: ";​
cin >> age;

2.​cout (Output Stream):


○​ Outputs data to the console.
○​ Syntax: cout << data;
○​ Example:

char name[] = “Rohan”;​


cout << “Hello” << name << endl;

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>

using namespace std;

int main() {

int num;

double salary;

cout << "Enter an integer: ";

cin >> num; // Input integer

cout << "Enter your salary: ";

cin >> salary; // Input float

cout << "You entered integer: " << num << endl;

cout << "Your salary is: " << salary << endl;

return 0;

}
Output:

Enter an integer: 25

Enter your salary: 5000.50

You entered integer: 25

Your salary is: 5000.50

Key Points:

●​ Use cin for input and cout for output.


●​ Input and output can be formatted using manipulators like fixed,
setprecision, etc.
●​ The << and >> operators are overloaded to work with streams in
C++.
Object-Oriented Programming (OOP)

Definition

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


organizes software design around objects. Objects represent
real-world entities and encapsulate data and behavior in a single unit.
OOP allows the creation of modular, reusable, and scalable software.

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

●​ Modularity: Code is organized into classes and objects, making


it easier to maintain and debug.
●​ Reusability: Classes can be reused across different programs
via inheritance and object instantiation.
●​ Scalability: Supports large and complex systems by breaking
them into smaller, manageable components.
●​ Security: Encapsulation provides data hiding and protects object
integrity.
●​ Real-World Mapping: Models real-world systems effectively by
using objects that represent entities.

Examples of OOP in Real Life

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

●​ Origin: The concept of OOP emerged in the 1960s.


●​ Simula: Simula (1967) is considered the first OOP language.
●​ C++: Introduced in the 1980s by Bjarne Stroustrup, combining
OOP concepts with the power of C.
●​ Java: Popularized OOP further with features like platform
independence and a strong emphasis on objects.
Character Sets and Tokens:

●​ Same as C.

Variable Declaration and Expression:

●​ 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.

Dynamic Memory Allocation with New and Delete:

●​ 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

delete ptr; // Deallocate memory

Condition and Looping:

●​ 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\") {

cout << \"Hello, \" << name;

greet(); // Outputs: Hello, Guest

Pass and Return by Reference:

●​ Different in C++:
1.​C++ introduces references (int &ref) to pass and return
variables by reference without pointers.

Example:​
void increment(int &x) {

x++;

Array, Pointer, and String:

●​ 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;

Employee(string n, int a) { name = n; age = a; }

};

Enumeration Data Type:

●​ 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

●​ Definition: Objects represent real-world entities that have state


and behavior.
●​ State: Represented by attributes or data members.
●​ Behavior: Defined by methods or member functions.
●​ Example: A "Car" object might have attributes like color, model,
and speed, and behaviors like start(), accelerate(), and stop().

Classes

●​ Definition: A class is a blueprint or template for creating objects.


●​ Attributes and Methods:
○​ Attributes define the data members of the class.
○​ Methods define the behaviors associated with the class.
●​ Encapsulation: Combines data and functions in a single unit
(class).

Relationship Between Objects and Classes

1.​Class: Defines properties and behaviors.


2.​Object: Is an instance of a class.
○​ When a class is defined, no memory is allocated.
○​ Memory is allocated only when an object is created from
the class.
Syntax

class ClassName {

// Attributes (data members)

public:

int attribute1;

float attribute2;

// Methods (member functions)


void method1() {

// Method body

};

Example: Defining and Using Classes and Objects


#include<iostream>

using namespace std;

// Define a class

class Car {

public:

// Attributes

string brand;

string color;

int speed;

// Method to display car details

void displayDetails() {

cout << "Brand: " << brand << endl;

cout << "Color: " << color << endl;

cout << "Speed: " << speed << " km/h" << endl;

// Method to accelerate the car

void accelerate(int increment) {

speed += increment;

cout << "Car accelerated to " << speed << " km/h." << endl;

}
};

int main() {

// Create an object of the Car class

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

Speed: 100 km/h

Car accelerated to 150 km/h.

Advantages of Using Classes and Objects

1.​Encapsulation: Combines attributes and methods, making code


modular and easier to maintain.
2.​Reusability: Classes can be reused across programs to create
multiple objects.
3.​Abstraction: Simplifies complex systems by focusing on
relevant details.
4.​Real-World Modeling: Makes it easier to model and simulate
real-world systems in code.
Features of C++ and Concept of OOP

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>

using namespace std;

class Calculator {

public:

void add(int a, int b) {

cout << "Sum: " << a + b << endl;

void subtract(int a, int b) {

cout << "Difference: " << a - b << endl;

private:

void internalLogic() {

// Hidden implementation details

}};
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>

using namespace std;

class Account {

private:

int balance;

public:

void setBalance(int b) {

balance = b;

int getBalance() {

return balance;

};

int main() {

Account acc;

acc.setBalance(1000);

cout << "Account Balance: " << acc.getBalance() << endl;

return 0;

Output:

Account Balance: 100


3. Inheritance

●​ 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>

using namespace std;

class Animal {

public:

void eat() {

cout << "This animal eats food." << endl;

};

class Dog : public Animal {

public:

void bark() {

cout << "The dog barks." << endl;

};

int main() {

Dog dog;

dog.eat(); // Inherited from Animal


dog.bark();

return 0;

Output:

This animal eats food.

The dog barks.


Access Control Table

Base Class public protected private


Member Inheritance Inheritance Inheritance

public Remain public in Become Become private


Members derived class protected in in derived class
derived class

protected Remain Remain Become private


Members protected in protected in in derived class
derived class derived class

private Not accessible Not accessible Not accessible


Members

Type Effect

Public Keeps access levels as they are in the base class.

Protected Public members become protected; protected


members remain protected.

Private Public and protected members become private.


4. Polymorphism

●​ 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.

Example 1: Function Overloading (Compile-time Polymorphism):


#include<iostream>

using namespace std;

class Math {

public:

int add(int a, int b) {

return a + b;

double add(double a, double 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

Sum (double): 31.00000

Example 2: Virtual Functions (Run-time Polymorphism):


#include<iostream>

using namespace std;

class Shape {

public:

virtual void draw() {

cout << "Drawing a shape." << endl;

};

class Circle : public Shape {

public:

void draw() override {

cout << "Drawing a circle." << endl;

};

int main() {

Shape *shape;

Circle circle;

shape = &circle;

shape->draw(); // Calls Circle's draw()

return 0;

Output: Drawing a circle.


Constructors and Destructors in C++

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

-​ Definition: A constructor that takes no arguments or has default


arguments.
-​ Purpose: Automatically initializes objects with default values.
Example:
#include<iostream>
using namespace std;
class Person {
public:
string name;
int age;
// Default Constructor
Person() {
name = "Unknown";
age = 0;
}
void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}};
int main() {
Person p; // Default constructor is called
p.display();
return 0;
}
Output:
Name: Unknown, Age: 0

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.

// Destructor is automatically called when 'p' goes out of scope

Aspect Constructor Destructor

Purpose Initializes an object Cleans up resources


used by the object

Name Same as the class Same as the class


name name, prefixed with ~

Arguments Can take arguments Cannot take


(parameterized arguments
constructor)

Return Type No return type No return type

Call Timing Automatically called Automatically called


when the object is when the object is
created destroyed

You might also like