Unit - I
Introduction to C++
Difference Between C and
C++: C C++
C was developed by Dennis
C++ was developed by Bjarne
Ritchie between the year 1969
Stroustrup in 1979.
and 1973 at AT&T Bell Labs.
C does no support C++ supports polymorphism,
polymorphism, encapsulation, encapsulation,
and inheritance which means and inheritance because it is
that C does not support object an object oriented
oriented programming. programming language.
C is (mostly) a subset of C++. C++ is (mostly) a superset of C.
Data is hidden by the
C does not support information Encapsulation to ensure that data
hiding. structures and operators are used
as intended.
C++ is known as hybrid language
For the development of code, C
because C++ supports
supports procedural
both procedural and object
programming.
oriented programming paradigms.
Data and functions are separated Data and functions are
in C because it is a procedural encapsulated together in form of
programming language. an object in C++.
There are 32 keywords in the C There are 97 keywords in the C++
Reference variables are not Reference variables are supported
supported by C. by C++.
Virtual and friend functions are not Virtual and friend functions are
supported by C. supported by C++.
C does not support inheritance. C++ supports inheritance.
scanf() and printf() functions are used for cin and cout are used for input/output in
input/output in C. C++.
C does not support overloading C++ does support overloading
File extension is “.cpp” or “.c++” or “.
File extension is “.c”
cc” or “.cxx”
Instead of focusing on data, C C++ focuses on data instead of
focuses on method or process. focusing on method or procedure.
Object-Oriented Technology (OOT)
Definition
• is a programming and design approach based on the concept
of "objects", which are instances of classes.
These objects can contain data (attributes) and methods
(functions) that
operate on the data.
Class: A blueprint or template for creating objects.
Object: A real instance of a class.
Key Concepts of Object-Oriented
Technology
• Encapsulation
It is the process of bundling data (variables) and the methods (functions) that
operate on that data into a single unit (class). Example : Capsule
• Inheritance
one new class is derived from one base class Ex Parent and child
Polymorphism
It means "many forms" — the ability of a function, method, or operator to behave
differently based on the object or context in which it is used.
• Abstraction
It refers to the process of hiding the internal implementation details and showing
only the essential features of an object.
Advantages of Object-Oriented Technology
Modularity
It refers to the design principle where a system is divided into separate components
or modules.
Each module is a self-contained unit that handles a specific functionality.
Example:
Imagine a Banking Application: Account module handles user accounts, Transaction
module handles
money transfers, Report module generates statements.
These modules can work independently but still communicate when needed
• Reusability
Objects and classes can be reused across different programs.
(Saves development time,Reduces errors,Supports faster development)
• Scalability
Easier to manage and expand with growing complexity.
• Maintainability
Easier to understand, debug, and modify.
• Efficiency
Helps in reducing code duplication and increasing code reuse through inheritance.
Conventional Programming
Definition:
Conventional Programming refers to the traditional way
of writing programs where the focus is on writing
sequences of instructions that tell the computer exactly
what to do, step by step.
This approach is often procedural, meaning the program
is divided into functions or procedures, and data is separate
from code.
Key Features:
• Procedures/Functions: The basic building blocks are procedures or
functions that perform specific tasks.
• Global Data: Data is often stored in global variables that can be
accessed by any procedure in the program.
• Top-Down Approach: Programs are typically designed using a top-
down approach, starting with a high-level design and breaking it
down into smaller functions or procedures.
• Sequence Control: Control flow is explicitly managed through
sequences of commands, loops, and conditionals.
#include <stdio.h>
// Function to add two numbers
int add(int a, int b) {
return a + b;
}
// Main function
int main() {
int num1 = 5, num2 = 3;
int sum = add(num1, num2);
printf("Sum: %d\n", sum);
return 0;
}
Disadvantages of Conventional Programming:
Lack of Modularity:
Functions and data are often not encapsulated,
leading to difficulties in managing and
maintaining large codebases.
Example: If global variables are used extensively,
any function can modify them, leading to potential
bugs and unintended side effects.
Code Reusability:
Conventional programming does not promote code reuse
as effectively as object-oriented programming.
Example: Without the use of classes and objects, creating
reusable components is more challenging.
Difficulty in Managing Complexity:
As programs grow larger, the complexity increases,
making it harder to manage, understand, and debug the
code.
Example: A large program with many interconnected
functions can become difficult to track and modify.
Poor Data Handling:
Data and functions are separate entities, leading to poor
data handling and organization.
Example: Structuring complex data relationships and
behaviors requires extensive function management.
Maintenance Challenges:
Maintaining and updating conventional programs can be
time-consuming and error-prone.
Example: Changes in one part of the code can have
ripple effects, causing issues in other parts of the program.
Scalability Issues:
Conventional programming is not well-suited for large-scale
software development.
Example: Adding new features or scaling the application
requires significant restructuring of the existing code.
Introduction of
Object Oriented
Programming
Introduction of Object Oriented
Programming
• Object-Oriented Programming or OOPs refers to
languages that use objects in programming.
• Object-oriented programming aims to implement
real-world entities like inheritance, hiding,
polymorphism, etc in programming.
• The main aim of OOP is to bind together the data
and the functions that operate on them so that no
other part of the code can access this data except
that function.
OOPs Concepts:
• Class • Inheritance
• Objects • Polymorphism
• Data Abstraction • Dynamic Binding
• Encapsulation • Message Passing
Class:
• A group of objects that share common properties for data part and
some program part are collectively called as class.
• Class is a like a Blueprint
• In C ++ a class is a new data type that contains member variables and
member functions that operate on the variables.
For Example:
• Consider the Class of Cars.
• There may be many cars with different names and brands but all of
them will share some common properties like all of them will have 4
wheels, Speed Limit, Mileage range, etc.
• So here, Car is the class, and wheels, speed limits, mileage are their
properties.
Class can be defined as a blueprint of the object. It is
basically a collection of objects which act as building
blocks.
• Class Syntax:
class classname
{
Access - Specifier:
Member Varibale Declaration;
Member Function Declaration;
}
Example
If fruit has been defined as a class then the statement
fruit mango
will create an object mango belonging the class fruit.
OBJECTS
• Objects are the basic run-time entities in an object-oriented system.
• They may represent a person, a place, a bank account, a table of data
or any item that the program must handle.
• The fundamental idea behind object oriented approach is to combine
both data and function into a single unit and these units are called
objects.
Syntax to create an Objects:
classname objectname=new classname();
Student s1; // declares s1
s1 = new Student(); // allocates space
Student s1 = new Student(); // does both
• An object doesn't exist until an instance of the class has
been created; the class is just a definition. When the object
is physically created, space for that object is allocated
in RAM
• It is possible to have multiple objects created from one class.
• Main Difference Between Class and Objects:
– Object takes Separate Memory.
– For Class, no memory is allocated.
Data Abstraction:
• Data abstraction is one of the most essential and important
features of object-oriented programming.
• It refers to the process of hiding the internal
implementation details and showing only the essential
features of an object.
• Consider a real-life example of a man driving a car. The man
only knows that pressing the accelerators will increase the
speed of the car or applying brakes will stop the car, but he
does not know about how on pressing the accelerator the speed
is increasing, he does not know about the inner mechanism of
the car or the implementation of the accelerator, brakes, etc in
the car.
Encapsulation:
• Encapsulation is defined as the wrapping up of data
under a single unit.
• It is the mechanism that binds together code and the data
it manipulates.
• In Encapsulation, the variables or data of a class are
hidden from any other class and can be accessed only
through any member function of their class in which
they are declared.
• As in encapsulation, the data in a class is hidden from
other classes, so it is also known as data-hiding.
Example of Encapsulation:
• Consider a real-life example of encapsulation, in a company, there are
different sections like the accounts section, finance section, sales section,
etc.
• The finance section handles all the financial transactions and keeps
records of all the data related to finance. Similarly, the sales section
handles all the sales-related activities and keeps records of all the sales.
• Now there may arise a situation when for some reason an official from
the finance section needs all the data about sales in a particular month.
• In this case, he is not allowed to directly access the data of the sales
section. He will first have to contact some other officer in the sales section
and then request him to give the particular data.
• This is what encapsulation is. Here the data of the sales section and the
employees that can manipulate them are wrapped under a single name
“sales section”.
Example code
class Car {
private:
int speed;
public:
void setSpeed(int s) {
speed = s;
}
int getSpeed() {
return speed;
}
};
Inheritance
• In OOP the concept of inheritance provides the idea of
reusability. This means that we can add additional features to
an existing class without modifying it.
• It is classifieds into different types, they are
• Single level inheritance
• Multiple Inheritance
• Multi-level inheritance
• Hybrid inheritance
• Hierarchial inheritance
29
Example code
class Vehicle {
public:
void move() {
cout << "Vehicle is moving\n";
}
};
class Car : public Vehicle {
public:
void honk() {
cout << "Car is honking\n";
}
};
Polymorphism:
❖ The word polymorphism means having many forms.
❖ In simple words, we can define polymorphism as the
ability
of a message to be displayed in more than one form.
❖ For example, A person at the same time can have
different characteristics.
❖ Like a man at the same time is a father, a husband, an
employee.
❖ So the same person posses different behavior in different
situations.
❖ This is called polymorphism.
Example code
class Animal
{
public:
virtual void sound() {
cout << "Animal makes a
sound\n";
}
class Dog : public Animal
{
public:
void sound() override {
cout << "Dog barks\n";
}
};
class Cat : public Animal
{
public:
void sound() override {
cout << "Cat meows\n";
}
};
Dynamic Binding:
• Dynamic Binding (also called Late Binding) is a concept in Object-
Oriented Programming where the method to be called is
determined at runtime, not at compile time.
• Dynamic Method Binding One of the main advantages of
inheritance is that some derived class D has all the members of its
base class B.
• Once D is not hiding any of the public members of B, then an object
of D can represent B in any context where a B could be used.
• This feature is known as subtype polymorphism.
Message Passing:
• Message Passing is a key concept in Object-Oriented
Programming (OOP) where objects communicate with each other
by sending and receiving messages (usually in the form of
method calls).
• When an object wants another object to perform a task, it sends a
message (i.e., calls a method) to that object.
• A message for an object is a request for execution of a procedure
and therefore will invoke a function in the receiving object that
generates the desired results.
• Message passing involves specifying the name of the object, the
name of the function, and the information to be sent.
Disadvantages of OOP
• The length of the programmes developed using OOP language is
much larger than the procedural approach. Since the programme
becomes larger in size, it requires more time to be executed that
leads to slower execution of the programme.
• We can not apply OOP everywhere as it is not a universal language.
It is applied only when it is required. It is not suitable for all types of
problems.
• Programmers need to have brilliant designing skill and
programming skill along with proper planning because using OOP is
little bit tricky.
• OOPs take time to get used to it. The thought process involved in
object-oriented programming may not be natural for some people.
• Everything is treated as object in OOP so before applying it we need
Structure of c++ program
HEADERS
CLASS DECLARATION
MEMBER FUNCTION
DEFINITIONS
MAIN FUNCTION
41
Headers
#include is a specific preprocessor command that effectively copies and pastes
the entire text of the file, specified between the angle brackets, into the source
code .
The file <iostream>, which is a standard file that should come with the C++
compiler, is short for input-output streams. This command contains code for
displaying and getting an input from the user.
Class Declaration or Definition
A class is an organization of data and functions which operate on them. Data types
are called data members and the functions are called member functions. The
combination of data members and member functions constitute a data object or
simply an object.
Member Functions
These are the various operations that can be performed to data members of that
class. We can declare any number of member functions of any type in a class.
Member functions are access using object and dot operator.
Main function section
The starting point of all C++ programs is the main function.
This function is called by the operating system when your program is executed by
the computer.
• Namespaces:
• A namespace permits grouping of various entities like classes, objects, functions, and
various C++ tokens, etc. under a single name.
• Any user can create separate namespaces of its own and can use them in any other
program.
• In the below snippets, namespace std contains declarations for cout, cin, endl, etc.
statements.
• using namespace std;
• Namespaces can be accessed in multiple ways:
• using namespace std;
• using std :: cout;
Structure of C++
// Preprocessor Directives
#include <iostream> // For input and output
// Global Variables
int globalVar = 10; // A global variable
// Function Declarations
void printMessage(); // Declaration of a function that prints a message
// Main Function
int main() {
// Local Variables
int localVar = 5; // A local variable
// Print the global and local variable values
std::cout << "Global Variable: " << globalVar << std::endl;
std::cout << "Local Variable: " << localVar << std::endl;
// Call a function
printMessage();
return 0; // End of the program
}
// Function Definitions
void printMessage() {
std::cout << "Hello, World!" << std::endl;
}
Header vs Library