Professional Documents
Culture Documents
● Readability and Clarity: A good programming language is designed to be easily readable and
understandable, making it easier for developers to write, maintain, and debug code.
● Expressiveness: A language with high expressiveness allows developers to accomplish more
with less code, making it concise and reducing the chance of errors.
● Portability: Good programming languages are designed to be portable across different
platforms and architectures, allowing code to run on various systems without major
modifications.
● Scalability: They can be used for small projects as well as large-scale applications, adapting to
the needs of projects of varying complexity.
● Abstraction: Good programming languages offer levels of abstraction, allowing developers to
work at different levels of detail and complexity.
● Performance: While high-level languages often prioritize ease of use and abstraction, good
programming languages also provide efficient performance for computationally intensive tasks.
● Flexibility: They allow developers to choose from multiple programming paradigms (e.g.,
procedural, object-oriented, functional), supporting diverse coding styles and approaches.
● Community and Ecosystem: A strong community and ecosystem with libraries, frameworks,
and tools contribute to the popularity and practicality of a programming language.
● Error Handling: Good programming languages provide effective error handling mechanisms,
making it easier for developers to detect and handle errors in their code.
● Security: Languages that prioritize security features and practices help developers write more
secure code and reduce the risk of vulnerabilities.
● Standardization: Well-defined standards for the language ensure consistency and
interoperability among different implementations and versions.
● Documentation and Support: A good programming language is well-documented, with ample
resources and community support available for developers to learn and troubleshoot.
● Compatibility and Integration: Integration with other languages and technologies allows
developers to leverage existing code and tools seamlessly.
● Consistency and Orthogonality: Good programming languages exhibit consistent behavior
and logical rules, minimizing surprises and unexpected interactions.
● Maintainability: They facilitate code maintainability by encouraging clean code practices and
modularization.
● Robustness: Good programming languages handle errors gracefully and avoid unexpected
program crashes.
● Innovation: Constant innovation and improvements keep the language relevant and up-to-date
with emerging trends and requirements.
● Ease of Debugging: Good programming languages offer debugging tools and features that
simplify the process of identifying and fixing issues in code.
● Performance Optimization: The language allows for performance optimizations without
sacrificing code readability and maintainability.
Paradigms:
⮚ What is Procedure Oriented Programming (POP)?
POP follows a step-by-step approach to break down a task into a collection of variables and routines
(or subroutines or functions) through a sequence of instructions. Each step is carried out in order in a
same manner so that a computer can understand what to do. The program is divided into small parts
called functions and then it follows a series of computational steps to be carried out in order.
It follows a top-down approach to actually solve a problem,. Procedures correspond to functions
and each function has its own purpose. Dividing the program into functions is the key to procedural
programming. So a number of different functions are written in order to accomplish the tasks.
As most of the functions share global data, they move independently around the system from function
to function, thus making the program vulnerable. These basic flaws gave rise to the concept of
object-oriented programming which is more secure.
4 Adding new data and functions is not easy. Adding new data and function is easy.
Procedural programming does not have any Object-oriented programming provides data
5
proper way of hiding data so it is less secure. hiding so it is more secure.
Procedural programming uses the concept of Object-oriented programming uses the concept of
10
procedure abstraction. data abstraction.
12 Objects linked with message passing Functions linked with parameters passing
13 Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.
⮚ Logical Programming is a type of programming paradigm that uses logic circuits to control
how facts and rules about the problems within the system are represented or expressed. In it,
logic is used to represent knowledge, and inference is used to manipulate it. It tells the model
about how to accomplish a goal rather than what goal to accomplish.
These are specially designed to manage and handle These are specially designed for fault diagnosis,
symbolic computation and list processing natural language processing, planning, and
applications. machine learning.
Its main aim is to reduce side effects that are Its main aim is to allow machines to reason
accomplished by isolating them from the rest of the because it is very useful for representing
software code. knowledge.
Some languages used in functional programming Some languages used for logic programming
include Clojure, Wolfram Language, Erland, OCaml, include Absys, Cycl, Alice, ALF (Algebraic logic
etc. functional programming language), etc.
It usually supports the functional programming It usually supports the logic programming
paradigm. paradigm.
Features of OOP
The main features of object oriented programming are as follows:
● Classes
● Objects
● Abstraction
● Polymorphism
● Inheritance
● Encapsulation
Classes and Objects
Classes:
A class is a way to bind data and functions together in a single data type. The variables and functions
enclosed in a class are called data members and member functions. Since classes by default are
private, class allows the data (and functions) to be hidden if necessary from external use.This
mechanism of binding data and functions that operate on that data is call data encapsulation. This
mechanism of hiding data of a class from the outside world (other classes) so that any access to it either
intentionally or unintentionally can’t modify the data is called data hiding.
Class Declaration:
A class specification has two parts:
(I) Class Declaration
(II) Class Function definitions
The class declaration describes the type and scope of its member. The class definitions describe how
the class functions are implemented. The general form of class declaration is
Creating Object:
An object is an instance of a class. In general a class is a user defined data type, while an object is an
instance of an class.
creates variables S1, S2 of type student. Once the objects are declared memory is allocated. Objects can
also
be created by placing their names immediately after the closing brace.
Advantages of Abstraction
The advantages of abstraction are as follows:
● It enables code reuse by avoiding code duplication.
● It enhances software security by making only necessary information available to the users
and hiding the complex ones.
Example:
You can have a parent class called “Shape” and other classes like Square, Circle, Rectangle, etc.
Since all these are also shapes, they will have all the properties of a shape so that they can
inherit the class Shape.
2. Inheritance : The process by which one class acquires the properties and functionalities of
another class. Inheritance provides the idea of reusability of code and each sub class defines
only those features that are unique to it.
● Inheritance is one of the most important features of object oriented programming. It allows
a class to inherit the properties and methods of another class called the parent class, the base
class, or the super-class.
● The class that inherits is called the child class or sub-class.
● It helps to avoid duplication of codes by allowing code reuse as you need not define the
same methods and properties present in a super-class in the sub-classes again. The sub-class
can simply inherit them.
3. Polymorphism : Polymorphism is a feature that allows one interface to be used for a general
class of actions. It’s an operation may exhibit different behavior in different instances.
Method Overloading
Methods overloading is a type of compile-time polymorphism using which you can define various
functions with the same name but different numbers of arguments. The function call is resolved at
compile time, so it's a type of compile-time polymorphism. Here resolution of the function call implies
binding to the correct function definition depending on the arguments passed in the function call.
Example:
You can create a function “add”. Now, when you pass two integers to this function, it will return their
sum, while on passing two strings, it will return their concatenation.
So, the same function acts differently depending on the input data type.
Method Overriding
Method Overriding is a type of run-time polymorphism. It allows overriding a parent class’s method by
a child class. Overriding means that a child class provides a new implementation of the same method it
inherits from the parent class.
These function calls are resolved at run-time, so it's a type of runtime polymorphism.
Example:
You can have a parent class called “Shape” with a method named “findArea” that calculates and
returns the area of the shape. Several sub-classes inherit from the “Shape,” like Square, Circle,
Rectangle, etc. Each of them will define the function “findArea” in its way, thus overriding the
function.
Example:
You can have some private variables in a class that you can't access outside the class for security
reasons. Now, to read or change the value of this variable, you can define public functions in the class
which will perform the read or writes operations.
Message Passing
Message passing refers to the process of passing a message, or data, between different objects or
components in a program. This can be done in many ways, such as function calls, events, or
inter-process communication. The specific implementation of message passing will depend on the
program's design and the system's needs.
Data types
Variables
Variables in C++ is a name given to a memory location. It is the basic unit of storage in a program.
The value stored in a variable can be changed during program execution.
A variable is only a name given to a memory location, all the operations done on the variable effects
that memory location.
In C++, all the variables must be declared before use.
Types of Variables
There are three types of variables based on the scope of variables in C++
● Local Variables
● Instance Variables
● Static Variables
Local Variables: A variable defined within a block or method or constructor is called a local variable.
● These variables are created when entered into the block or the function is called and destroyed
after exiting from the block or when the call returns from the function.
● The scope of these variables exists only within the block in which the variable is declared. i.e.
we can access this variable only within that block.
● Initialization of Local Variable is Mandatory.
Instance Variables: Instance variables are non-static variables and are declared in a class outside any
method, constructor, or block.
● As instance variables are declared in a class, these variables are created when an object of the
class is created and destroyed when the object is destroyed.
● Unlike local variables, we may use access specifiers for instance variables. If we do not specify
any access specifier then the default access specifier will be used.
● Initialization of Instance Variable is not Mandatory.
● Instance Variable can be accessed only by creating objects.
Static Variables: Static variables are also known as Class variables.
● These variables are declared similarly as instance variables, the difference is that static variables
are declared using the static keyword within a class outside any method constructor or block.
● Unlike instance variables, we can only have one copy of a static variable per class irrespective
of how many objects we create.
● Static variables are created at the start of program execution and destroyed automatically when
execution ends.
● Initialization of Static Variable is not Mandatory. Its default value is 0
● If we access the static variable like the Instance variable (through an object), the compiler will
show the warning message and it won’t halt the program. The compiler will replace the object
name with the class name automatically.
● If we access the static variable without the class name, the Compiler will automatically append
the class name.
Here, we have used the keyword const to declare a constant named LIGHT_SPEED. If we try to
change the value of LIGHT_SPEED, we will get an error.
A constant can also be created using the #define preprocessor directive.
Data Members
Data members include members that are declared with any of the fundamental types, as well as other
types, including pointer, reference, array types, bit fields, and user-defined types. You can declare a
data member the same way as a variable, except that explicit initializers are not allowed inside the class
definition. However, a const static data member of integral or enumeration type may have an explicit
initializer.
class Test
{ void getA() { a=10; }
private: ...;
int a; …
float b; };
char *name;
Member Functions
● A member function of a class is a function that has its definition or its prototype within the class
definition like any other variable. It operates on any object of the class of which it is a member,
and has access to all the members of a class for that object.
● A Member function is a function that is declared as a member of a class. It is declared inside the
class in any of the visibility modes i.e. public, private, and protected, and it can access all the
data members of the class. If the member function is defined inside the class definition, it can
be defined directly inside the class; otherwise, we need to use the scope resolution operator (::)
to declare the member function in C++ outside the class
● The main aim of using the member function is to provide modularity to a program, which is
generally used to improve code reusability and to make code maintainable.
public:
// member function declared inside class
// but defined outside
void displayStudent();
3. Public mode:
When we inherit a derived class from a base class with public visibility mode, the public members and
protected members of the base class will be inherited as public members and protected members
respectively of the derived class.
#include <iostream> class X{
private: //protected: int b; inherited from class X
int a; //public: int c; inherited from class X
protected: };
int b; int main()
public: {
int c; //Only int c can be accessed in main function
}; using Class Y object as it is public;
class Y : public X{ Y obj;
//As the visibility mode is public the protected std::cout<<obj.c;
members of class X becomes protected member return 0;
for class Y and public members of class X }
becomes public member for class Y
Constructors
Declaration and Definitions:
A constructor is a special member function which is used to initialize the objects of a class.
The general syntax is as follows:
class classname
{
private: ……
public:
classname( Parameter list ); //constructor declaration
};
classname : : classname(Parameter list )
{ //constructor definition
……………
}
Default Constructor
// Default constructor called automatically
#include <iostream>
// when the object is created
using namespace std;
construct c;
class construct
cout << "a: " << c.a << endl
{
<< "b: " << c.b;
public:
return 0;
int a, b;
}
}; class Point
{
private:
int main() int x, y;
{
public:
{
// Parameterized Constructor len=b.len;
Point(int x1, int y1) bre=b.bre;
{ hei=b.hei;
x = x1; count++;
y = y1; cout<<"\n number of object
} created are \t "<<count;
}
int getX()
{
return x;
} void volume()
int getY() {
{ vol=len*bre*hei;
return y; cout<<"\n Volume is"<<vol;
} }
}; };
int main()
int main() {
{ box b;
// Constructor called box b3(b);
Point p1(10, 15);
b3.volume();
// Access values assigned by constructor return 0;
cout << "p1.x = " << p1.getX() << ", p1.y = " << }
return 0;
} Derived class constructor
Output: #include<iostream>
p1.x = 10, p1.y = 15 using namespace std;
//multiple inheritance -
Copy Constructor class student
{
#include<iostream> protected:
using namespace std; int rno;
int count=0; public:
class box student(int prn)
{ {
int len,bre,hei,vol; rno=prn;
public: cout<<"\n rno = :"<<rno;
box () }
{ };
}
box(box & b)
class studmarks public:
{ student(int prn)
protected: {
int m1; rno=prn;
public: cout<<"\n rno = :"<<rno;
studmarks(int mark) }
};
{
m1=mark;
class studmarks
cout<<"\n m1 = :"<<m1; {
} protected:
}; int m1;
public:
class studrecord:public student, public studmarks(int mark)
studmarks {
{ m1=mark;
public: cout<<"\n m1 = :"<<m1;
studrecord(int a, int }
b):student(a),studmarks(b) };
{}
class studrecord:public student, public
};
studmarks
{
int main() public:
{ int t;
int x,y; studrecord(int a, int b, int
cout<<"enter data student prn and mark"; c):student(a),studmarks(b)
cin>>x>>y; {
studrecord s(x,y); t=c;
return 0; cout <<"sportmark="<<t;
} }
};
int main()
#include<iostream> {
using namespace std; int x,y,z;
cout<<"enter data student prn and mark,
//multiple inheritance - sportmark";
class student cin>>x>>y>>z;
{ studrecord s(x,y,z);
protected: return 0;
int rno; }
Destructors
A destructor is a special member function which is used to destroy the object that has been created by
constructor.
The main characteristics are
a. The destructor is having same name as name of class except that it is preceded y tild ( ~ ).
b. They cannot be declared static, const.
c. They should have public access in class declaration.
d. A destructor has no return type and neither it takes any argument.
Static Data Members are those which are declared by using the Static Keyword in front of the
Data Members. Means Put the Static Keyword in front of the Variables. And Static Data
Members always have Default values as\ 0 for int and Null for Strings. So that they will Never
Stores any Garbage values. Always remember that Static Data Members are always used in the
Static Member Functions. Means if a Member Functions wants to use a Static Data then we must
have to declare that Member Function as Static. And the Static Data Members are always
Assigned Some values from the outside from the Class.
Static Member Functions: The Static Member Functions are those which are declared by using
the Static in Front of the Member Function. And in this we use the Static Data Members. Any
Method can be converted into the Static just by Using the Static in front of the Member
Function.
For Accessing the Static data Member Function we doesn’t need to Create an Object of Class
and we will call the Function with the name of Class and Scope resolution Operator. So that
there will be no object and no Extra Memory is required to Store the Data of a Class.
Example
#include<iostream> {
using namespace std; cout<<"\nenter l,b,h\n";
class Box cin>>l>>b>>h;
{ }
static int count;
int l,b,h,vol; void volume()
public: {
++count;
void getdata() vol=l*b*h;
cout<<"\nvolume is "<<vol; {
} Box b1,b2;
b1.getdata();
static int showcount() b2.getdata();
{ b1.volume();
cout<<"\nNumber of objects created are b2. volume();
\t"<<count; Box::showcount();
} Box b3;
}; b3.getdata();
b3.volume();
int Box::count; Box::showcount();
}
int main()
Hence, friend functions can access private data members by creating object of the class.
Similarly we can also make function of some other class as friend, or we can also make an entire
class as friend class.
class Other {
void fun();
}; // making function of class Other as
friend here
class WithFriend friend void Other::fun();
{
private: // making the complete class as friend
int i; friend class Other;
public: };
void getdata(); // Member function of
class WithFriend
When we make a class as friend, all its member functions automatically become friend functions.
Inline Function
C++ provides inline functions to reduce the function call overhead. An inline function is a
function that is expanded in line when it is called. When the inline function is called whole code
of the inline function gets inserted or substituted at the point of the inline function call. This
substitution is performed by the C++ compiler at compile time. An inline function may increase
efficiency if it is small.
Syntax:
inline return-type function-name(parameters)
{
// function code
}
displayNum(5);
#include <iostream>
using namespace std; // second function call
displayNum(8);
inline void displayNum(int num) {
cout << num << endl; // third function call
} displayNum(666);
5
8
666
Why Inline Functions are Used
When the program executes the function call instruction the CPU stores the memory address of
the instruction following the function call, copies the arguments of the function on the stack, and
finally transfers control to the specified function. The CPU then executes the function code,
stores the function return value in a predefined memory location/register, and returns control to
the calling function. This can become overhead if the execution time of the function is less than
the switching time from the caller function to called function (callee).
For functions that are large and/or perform complex tasks, the overhead of the function call is
usually insignificant compared to the amount of time the function takes to run. However, for
small, commonly-used functions, the time needed to make the function call is often a lot more
than the time needed to actually execute the function’s code. This overhead occurs for small
functions because the execution time of a small function is less than the switching time.
Friend Function
Output
Sum: 13
Here, ClassB is a friend class of ClassA. So, ClassB has access to the members of classA.
In ClassB, we have created a function add() that returns the sum of numA and numB.
Since ClassB is a friend class, we can create objects of ClassA inside of ClassB.
Array of objects
Like array of other user-defined data types, an array of type class can also be created. The array
of type class contains the objects of the class as its individual elements. Thus, an array of a class
type is also known as an array of objects. An array of objects is declared in the same way as an
array of any built-in data type.
The syntax for declaring an array of objects is
1 class_name array_name [size] ;
To understand the concept of an array of objects, consider this example.
Example : A program to demonstrate the concept of array of objects
float price ;
#include<iostream> public:
using namespace std; void getdata ();
class books { void putdata ();
char tit1e [30]; };
void books :: getdata () { books book[size] ;
cout<<"Title:”; for(int i=0;i<size;i++) {
cin>>title; cout<<"Enter details o£ book "<<(i+1)<<"\n";
cout<<"Price:”; book[i].getdata();
cin>>price; }
} for(int i=0;i<size;i++) {
void books :: putdata () { cout<<"\nBook "<<(i+l)<<"\n";
cout<<"Title:"<<title<< "\n"; book[i].putdata() ;
cout<<"Price:"<<price<< "\n”; }
const int size=3 ; return 0;
} }
int main() {
Binding refers to the process of associating a method or function call with its actual
implementation during the program's execution. There are two main types of binding in
programming: static binding (also known as early binding) and dynamic binding (also known as
late binding). These concepts are particularly relevant in object-oriented programming
languages.
class Base {
public:
void show() {
cout << "Base show()" << endl;
}
};
class Derived : public Base {
public:
void show() {
cout << "Derived show()" << endl;
}
};
int main() {
Derived d;
Base *ptr = &d;
ptr->show(); // Static binding, calls Base's show() based on the pointer's type
return 0;
}
class Base {
public:
virtual void show() {
cout << "Base show()" << endl;
}
};
int main() {
Derived d;
Base *ptr = &d;
ptr->show(); // Dynamic binding, calls Derived's show() based on the actual object type
return 0;
}
In summary, static binding is resolved at compile time based on the declared type, whereas
dynamic binding is resolved at runtime based on the actual object type. Dynamic binding,
often associated with polymorphism, allows for more flexible and extensible code by enabling
the selection of the appropriate method implementation based on the object's runtime type.
Case Study
Demonstrate student database application using classes objects constructor, destructor
friend
function in c++ // Constructor to initialize the student
#include <iostream> object
#include <string> Student(std::string studentName, int
studentAge, int studentRollNumber)
class Student { : name(studentName),
private: age(studentAge),
std::string name; rollNumber(studentRollNumber) {
int age; std::cout << "Creating student: " <<
int rollNumber; name << std::endl;
}
public:
// Destructor to clean up the student std::cout << "Roll Number: " <<
object student.rollNumber << std::endl;
~Student() { }
std::cout << "Destroying student: "
<< name << std::endl; int main() {
} // Create student objects using the
constructor
// Friend function to display student Student student1("John Doe", 20, 101);
information Student student2("Jane Smith", 22,
friend void displayStudentInfo(const 102);
Student& student);
}; // Call the friend function to display
student information
// Friend function definition to display displayStudentInfo(student1);
student information displayStudentInfo(student2);
void displayStudentInfo(const Student&
student) { // The student objects will be destroyed
std::cout << "Name: " << student.name automatically when they go out of scope
<< std::endl; return 0;
std::cout << "Age: " << student.age << }
std::endl;
In this example, we define a Student class with private member variables name, age, and
rollNumber. The class has a constructor that takes arguments to initialize the object's data and a
destructor to clean up resources when the object goes out of scope.
The displayStudentInfo() function is declared as a friend of the Student class. It can access the
private member variables of Student objects and display their information.
In the main() function, we create two Student objects, student1 and student2, using the
constructor. Then, we call the displayStudentInfo() function to print the information of both
students. As the program ends, the destructor is automatically called for each Student object,
showing the clean-up process.