You are on page 1of 38

Unit I : Introduction to Object Oriented Programming

⮚ Roles of programming languages:

● Communication with Computers: Programming languages serve as a medium of


communication between humans and computers. They allow developers to write instructions
that computers can understand and execute.
● Algorithm Implementation: Programming languages enable the implementation of algorithms
and data structures, facilitating problem-solving and computational tasks.
● Software Development: They are essential for building software applications, ranging from
simple scripts to complex applications and systems.
● Abstraction: Programming languages provide levels of abstraction, allowing developers to
work at different levels of complexity and hide implementation details.
● Portability: Different programming languages have varying levels of portability, enabling code
to run on different platforms and architectures.
● Efficiency and Performance: The choice of programming language can significantly impact
the efficiency and performance of the resulting software.
● Domain-Specific Applications: Some programming languages are specialized for specific
domains, such as web development, data analysis, scientific computing, etc.
● Community and Ecosystem: Each programming language has its community of developers,
libraries, frameworks, and tools that support and enhance its capabilities.
● Innovation and Advancements: New programming languages often introduce innovative
features, paradigms, and concepts that influence other languages and improve development
practices.
● Language Paradigms: Programming languages can be categorized into different paradigms,
such as procedural, object-oriented, functional, and more, each offering unique approaches to
problem-solving.
● Learning and Education: Programming languages are fundamental in teaching computer
science concepts and programming skills to students and learners.
● Software Maintenance: Programming languages impact the ease of software maintenance and
updates, affecting code readability and maintainability.
● Automation and Scripting: Many programming languages are used for automating repetitive
tasks and writing scripts to streamline processes.
● Interoperability: They allow different software components written in various languages to
communicate and work together seamlessly.
● Security and Robustness: The choice of language can impact software security, vulnerability
risks, and robustness against errors and failures.
● Community and Collaboration: Programming languages foster collaboration through
open-source projects, where developers can contribute and improve shared codebases.
● Embedded Systems: Specific programming languages are used for developing software for
embedded systems, like microcontrollers and IoT devices.
● Data Manipulation: Programming languages are essential for data analysis, data processing,
and data manipulation tasks.
● AI and Machine Learning: Specialized programming languages and libraries are used
extensively in AI and machine learning applications.
● Game Development: Game developers rely on various programming languages to build and
optimize interactive and immersive gaming experiences.

⮚ Need to study programming languages:

● Foundation of Computer Science: Programming languages are fundamental to understanding


computer science concepts and principles.
● Problem Solving: Learning programming languages helps develop analytical and
problem-solving skills, enabling you to approach complex issues logically.
● Software Development: If you aspire to become a software developer, studying programming
languages is a prerequisite to writing code and building applications.
● Career Opportunities: Proficiency in programming languages opens up numerous job
opportunities in the IT industry.
● Innovation and Creativity: Programming languages provide a platform to express creativity
and bring innovative ideas to life through software solutions.
● Understanding Technology: As technology becomes increasingly prevalent, studying
programming languages helps you understand the world around you.
● Critical Thinking: Learning to code enhances critical thinking skills and improves your ability
to analyze problems and find efficient solutions.
● Adaptability: Programming languages evolve rapidly, and studying them helps you stay
adaptable in a dynamic tech landscape.
● Interdisciplinary Skills: Programming languages are used in various disciplines, such as data
science, web development, cybersecurity, etc., making them versatile skills.
● Automation and Efficiency: Programming allows you to automate repetitive tasks, making
processes more efficient and saving time.
● Enhanced Communication: Knowing how to code facilitates better communication with
technical teams, fostering collaboration and understanding.
● Building Personal Projects: Understanding programming languages empowers you to create
personal projects and turn your ideas into reality.
● Solving Real-world Issues: Through programming, you can develop solutions that address
real-world problems and have a positive impact on society.
● Logical Thinking: Coding exercises and programming challenges enhance your logical
thinking abilities.
● Appreciating Technology's Impact: Studying programming languages gives you insights into
how technology shapes various industries and aspects of life.
● Personal Growth: Learning programming languages can boost confidence and contribute to
personal growth as you overcome challenges and master new skills.
● Entrepreneurship Opportunities: Proficiency in programming opens doors for
entrepreneurship in the tech startup space.
● Understanding Software Engineering: Programming languages are the building blocks of
software engineering, enabling you to understand the software development life cycle.
● Continuous Learning: The tech industry is constantly evolving, and programming languages
demand continuous learning and skill updates.
● Empowering Others: Knowing programming languages allows you to contribute to
open-source projects and help others in the developer community.

⮚ Characteristics of good programming languages:

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

⮚ Object-Oriented Programming (OOP)


Object-oriented programming (OOP) is a software programming model constructed around objects.
This model compartmentalizes data into objects (data fields) and describes object contents and
behavior through the declaration of classes (methods).
Object-oriented programming allows for simplified programming. Its benefits include reusability,
refactoring, extensibility, maintenance and efficiency.
OR
Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects",
which may contain data, in the form of fields, often known as attributes; and code, in the form of
procedures, often known as methods.
● Object – An object is basically a self-contained entity that accumulates both data and
procedures to manipulate the data. Objects are merely instances of classes.
● Class – A class, in simple terms, is a blueprint of an object which defines all the common
properties of one or more objects that are associated with it. A class can be used to define
multiple objects within a program.

Sr. Procedural Oriented Programming Object-Oriented Programming

1 In procedural programming, the program is In object-oriented programming, the program is


divided into small parts called functions. divided into small parts called objects.
Procedural programming follows a top-down Object-oriented programming follows a bottom-up
2
approach. approach.

There is no access specifier in procedural Object-oriented programming has access


3
programming. specifiers like private, public, protected, etc.

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.

In procedural programming, overloading is not Overloading is possible in object-oriented


6
possible. programming.

In procedural programming, there is no concept In object-oriented programming, the concept of


7
of data hiding and inheritance. data hiding and inheritance is used.
Sr. Procedural Oriented Programming Object-Oriented Programming

In procedural programming, the function is more In object-oriented programming, data is more


8
important than the data. important than function.

Procedural programming is used for designing Object-oriented programming is used for


9
medium-sized programs. designing large and complex programs.

Procedural programming uses the concept of Object-oriented programming uses the concept of
10
procedure abstraction. data abstraction.

Code reusability absent in procedural Code reusability present in object-oriented


11
programming, programming.

12 Objects linked with message passing Functions linked with parameters passing

13 Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.

⮚ Functional Programming is a type of programming paradigm in which everything is done


with the help of functions and using functions as its basic building blocks. In it, we simply try
to bind each and everything in a purely mathematical functions’ style. Programs are generally
written at a higher level and are therefore much easier to comprehend.

⮚ 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.

Functional Programming Logical Programming

It is totally based on functions. It is totally based on formal logic.

In this programming paradigm, program statements


In this programming paradigm, programs are
usually express or represent facts and rules related
constructed by applying and composing functions.
to problems within a system of formal logic.
Functional Programming Logical Programming

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 reduces code redundancy, improves modularity,


It is data-driven, array-oriented, used to express
solves complex problems, increases maintainability,
knowledge, etc.
etc.

It usually supports the functional programming It usually supports the logic programming
paradigm. paradigm.

Testing is much easier as compared to logical Testing is comparatively more difficult as


programming. compared to functional programming.

It simply uses predicates. Here, the predicate is not


It simply uses functions.
a function i.e., it does not have a return value.

Ex. ALF (algebraic logical functional


Ex. Erland
programming language)

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

class <class name>


{
private: \\ by private we mean that members can be accessed only from within the class i.e
member data can be accessed by the member functions.
data members;
member functions;
protected: \\ by protected we mean that members can be accessed only by member functions
and friends of that class.
data members;
member functions;
public: \\ by public we mean that members can be accessed outside class also.
data members;
member functions;
};

Example: The following declaration illustrates the specification of a class student.


class student
{
int rollno;
float marks;
public:
void getdata ( );
void display ( );
};

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.

Example Let student be the name of class


student S1,S2;

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.

Example: class student


{ …..
}S,S2,S3;

Accessing Class members


After creating the object there is a need to access the class member. This can be done by using a dot ( .
) operator

Example: Function call statement


S1.getdata(129,704.5 ); assign value 129 to rollno and 704.5 to marks of object S1.
S1.display( ); will display value of data members.
Similarly the statement
S1.roll = 129; is invalid because data member is private

Main features of OOPS.


1. Abstraction: Abstraction means displaying only essential information and hiding the details.
Data abstraction refers to providing only essential information about the data to the outside
world, hiding the background details or implementation It refers to providing only essential
information to the outside world and hiding their background details, i.e., to represent the
needed information in program without presenting the details. Data abstraction is a
programming (and design) technique that relies on the separation of interface and
implementation. any C++ program where you implement a class with public and private
members is an example of data abstraction.

How to implement abstraction?


You can implement abstraction using classes that group the data members and function together.
Inside classes, you can choose the access specifiers for its members to control how they are
visible to the outside world. We can also create header files containing the implementations of
all the necessary functions. So, you can include the header file and call these functions without
getting into their implementation.

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.

There are two types of polymorphism:


● Compile-time polymorphism
● Run-time polymorphism

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.

4. Encapsulation: Encapsulation is a process of combining data members and functions in a


single unit called class. This is to prevent the access to the data directly, the access to them is
provided through the functions of the class

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.

Other Oops Features:


Dynamic Binding
Dynamic binding takes place during run time based on the type of object. Since it is delayed till the run
time, it is also called late binding or runtime binding. When the compiler cannot determine all the
information required to resolve a function call during compile time, these function calls are not bound
until run time.

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.

// Declaring a single variable


Data_type variable_name;

// Declaring multiple variables:


Data_type variable1_name, variable2_name, variable3_name;
A variable name can consist of alphabets (both upper and lower case), numbers, and the underscore ‘_’
character. However, the name must not start with a number.

Initialization of a variable in C++


Examples:
// Declaring float variable

Rules For Declaring Variable


● The name of the variable contains letters, digits, and underscores.
● The name of the variable is case sensitive (ex Arr and arr both are different variables).
● The name of the variable does not contain any whitespace and special characters (ex #,$,%,*,
etc).
● All the variable names must begin with a letter of the alphabet or an underscore(_).
● We cannot used C++ keyword(ex float,double,class)as a variable name.

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.

Instance Variable Vs Static Variable


Each object will have its own copy of the instance variable whereas We can only have one copy of a
static variable per class irrespective of how many objects we create.
Changes made in an instance variable using one object will not be reflected in other objects as each
object has its own copy of the instance variable. In the case of static, changes will be reflected in other
objects as static variables are common to all objects of a class.
We can access instance variables through object references and Static Variables can be
accessed directly using the class name.
The syntax for static and instance variables:
Constants
Constants, as the name suggests, have fixed values.
const int LIGHT_SPEED = 299792458;
LIGHT_SPEED = 2500 // Error! LIGHT_SPEED is a constant.

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.

Member Function inside the class/ Class as a abstract datatype


#include <iostream> {
using namespace std; cout << "Name: " << name << endl;
class Student//class definition cout << "ID: " << id << endl;
{ }
// member variables
int id; void setDetails(int studID, string studName){
string name; id = studID;
name = studName;
public: }
// member function declared and defined };
// inside class int main()
void displayStudent() {
Student s1; }
Output
s1.setDetails(1, "Naman"); Name: Naman
s1.displayStudent(); ID: 1

Problem with function definition inside:


If a function defined inside the class, it becomes inline and implicit expansion takes place, hence
performance decreases and recommended to define the function outside the class.

Member Function outside the class


Member functions are defined outside the class using scope resolution operator(::) as shown below –
return_Data_type class_name::function_name()
#include <iostream> s1.setDetails(1, "Naman");
using namespace std; s1.displayStudent();
class Student//class definition }
{ Output
// member variables Name: Naman
int id; ID:
string name;

public:
// member function declared inside class
// but defined outside
void displayStudent();

void setDetails(int studID, string studName);


};

// function definition outside the class


// using scope resolutor ::
void Student::displayStudent(){
cout << "Name: " << name << endl;
cout << "ID: " << id << endl;
}

// function definition outside the class


void Student::setDetails(int studID, string
studName){
id = studID;
name = studName;
}
int main()
{
Student s1;
Accessing private member function of a class
When a member function is public we can access that member fun directly by using (.) membership
operator anywhere
Example cube_obj.Len will be valid if len is public
However, a private member variable can not be accessed using dot(.) membership operator
Example : cube_obj.breadth will be invalid if breadth private
Hence A private member function is accessed by only another public function of the same class within
the body of the class

What is the visibility mode


In inheritance whenever the derived class inherits from the base class than which of the member of the
parent class can be accessible in the child class is controlled by the visibility mode. By default visibility
mode is always set to private.
Syntax is:
class derived_class_name :: visibility_mode base_class_name
{
//Lines of code
}
Types of Visibility Mode in C++
There are total 3 types of visibility mode in C++ that are:
● Private visibility mode,
● Protected visibility mode,
● Public visibility mode

1. Private visibility mode:


When we inherit a derived class from the base class with private visibility mode then the public and
protected members of the base class become private members of the derived class.
#include <iostream> //As the visibility mode is private none of the
class X{ member of base class is inherited to derived
private: class
int a; };
protected: int main()
int b; {
public: //Nothing can be accessed using Class Y object
int c; because there are no members in class Y.
}; return 0;
class Y : private X{ }

2. Protected visibility mode:


When we inherit a derived class from a base class with protected visibility mode the protected and
public members of the base class become protected members of the derived class
#include <iostream> //protected: int b,int c inherited from class X
class X{ };
private: int main()
int a; {
protected: //As the members in the class Y are protected
int b; they cannot be accessed in main using Class Y
public: object.
int c; return 0;
}; }
class Y : protected X{
//As the visibility mode is protected the
protected and public members of class X
becomes the protected members of Class Y

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

Calling constructor in two ways.


1. By calling the constructor implicitly (Implicit calling) time t1(11,11);
2. By calling the constructor explicitly (Explicit calling) time t1 = time(11,11);
A constructor is different from normal functions in following ways:
● Constructor has same name as the class itself
● Default Constructors don’t have input argument however, Copy and Parameterized Constructors
have input arguments
● Constructors don’t have return type
● A constructor is automatically called when an object is created.
● It must be placed in public section of class.
● If we do not specify a constructor, C++ compiler generates a default constructor for object
● A constructor may not be static.
● They do not have return type, not even void.
● They are used to initialize data members of a class.
● They cannot be inherited, though a derived class can call the base class constructor.
● They are used to allocate resources such as memory to the dynamic data members of a class.
● Constructor can have default arguments

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

// Default Constructor Output:


construct() a: 10
{ b: 20
a = 10; Parameterized Constructor
b = 20; #include <iostream>
} using namespace std;

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

The general syntax is as follows:

Program to demonstrate constructor and destructor function


class sample cout<<”\n Object dies”;
{ }
public: };
sample ( ) void main ( )
{ {
cout<<”\n Object is born”; sample S;
} cout<<endl<<”Main terminated”;
~sample ( ) }
{
The output shows when the constructor
and destructor are called. The destructor is
called for an object when it reaches the
end of its scope.
Note: Objects are destroyed in the reverse
order of creation.

Static Data Members and Static Member Function


We can define class members static using static keyword. When we declare a member of a class
as static it means no matter how many objects of the class are created, there is only one copy of
the static member.
A static member is shared by all objects of the class. All static data is initialized to zero when the
first object is created, if no other initialization is present. We can't put it in the class definition but
it can be initialized outside the class

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()

Friend functions in C++


Friend functions are actually not class member function. Friend functions are made to
give private access to non-class functions. You can declare a global function as friend, or a
member function of other class as friend.
For example:
class WithFriend WithFriend wf;
{ wf.i=10; // access to private data
int i; member
public: cout << wf.i;
friend void fun(); // global function as }
friend
}; int main()
{
void fun() fun(); //Can be called directly
{ }

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

int main() { return 0;


// first function call }

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.

Inline functions Advantages:


● Function call overhead doesn’t occur.
● It also saves the overhead of push/pop variables on the stack when a function is called.
● It also saves the overhead of a return call from a function.
● When you inline a function, you may enable the compiler to perform context-specific
optimization on the body of the function. Such optimizations are not possible for normal
function calls. Other optimizations can be obtained by considering the flows of the
calling context and the called context.
● An inline function may be useful (if it is small) for embedded systems because inline can
yield less code than the function called preamble and return.

Friend Function

Use of Friend Class in C++


● Friend class has numerous uses and benefits. Some of the primary use cases include:
● Accessing private and protected members of other classes (as you would know by now)
● Declaring all the functions of a class as friend functions
● Allowing to extend storage and access its part while maintaining encapsulation
● Enabling classes to share private members' information
Widely used where two or more classes have interrelated data members

The syntax for implementing a friend class is:


class ClassB;
class ClassA {
// ClassB is a friend class of ClassA
friend class ClassB;
... .. ...
}
class ClassB {
... .. ...
}
As you can see in the syntax, all you need to do is use the keyword friend in front of a class to
make it a friend class. Using this syntax will make ClassB a friend class of ClassA. Since ClassB
becomes the friend class, it will have access to all the public, private, and protected members of
ClassA. However, the opposite will not be true. That’s because C++ only allows granting the
friend relation and not taking it. Hence, ClassA will not have access to private members of
ClassB.

// C++ program to demonstrate the public:


working of friend class ClassA()
#include <iostream> {
using namespace std; numA=12;
class ClassB; }
class ClassA { };
private:
int numA; class ClassB {
friend class ClassB; private:
int numB;
return objectA.numA + numB;
public: }
ClassB() };
{
numb=1; int main() {
} ClassB objectB;
cout << "Sum: " << objectB.add();
int add() { return 0;
ClassA objectA; }

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.

1. Static Binding (Early Binding):


● Definition: Static binding occurs when the association between a method call and its
implementation is resolved at compile time. The decision about which method to call is
made based on the declared type of the variable or object at compile time.
● Usage: Static binding is commonly used in languages like C++ for non-virtual member
functions. When a method is declared as non-virtual, the compiler determines the
appropriate method to call based on the type of the object or variable at compile time.
This can lead to faster execution as the method resolution is known in advance.
● Example (C++

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

Dynamic Binding (Late Binding):


● Definition: Dynamic binding occurs when the association between a method call and its
implementation is resolved at runtime. The decision about which method to call is made
based on the actual type of the object or variable at runtime, rather than its declared type.
● Usage: Dynamic binding is associated with polymorphism and inheritance in
object-oriented programming. It is commonly used for virtual member functions.
Languages like C++ use the virtual keyword to mark a method as virtual, enabling
dynamic binding. This allows for more flexible and extensible code but can lead to a
slight runtime overhead due to the extra method resolution step.
● Example (C++

class Base {
public:
virtual 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(); // 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.

You might also like