Module1 C++

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 44

Module-1 (8 hours)

Introduction to Object Oriented Programming: Computer programming background- C++ overview.


First C++ Program -Basic C++ syntax, Object Oriented Programming : What is an object, Classes,
methods and messages, abstraction and encapsulation, inheritance, abstract classes, polymorphism.

Textbook 1: Chapter 1(1.1 to 1.8)


Introduction to Object Oriented Programming:
 C++ (pronounced "see plus plus") is a general-purpose programming language.
 It was developed by Bjarne Stroustrup as an extension of the C programming
language.
 The first release of C++ was in 1983.
 C++ finds extensive use in developing system and application software.
 It is also widely employed in game development.
 Embedded systems(smart watch,Mobile phone) often utilize C++ for programming
tasks.

NEED FOR C++:

1.Limitations of C
 Lack of Global View: Managing and understanding large C programs becomes difficult .
 Limited Reusability: C doesn't have features to easily reuse code.
 C doesn't have a garbage collector.
 C doesn't support any kind of polymorphism.
 C doesn't support object-oriented programming very well.
 C provides only limited support for avoiding namespace collisions.

2.Object Oriented Programming:


Origin and Purpose:
 Introduced to address limitations of C, specifically the lack of reusability and a global view
in large programs.
 Aims to provide a way to visualize and design software as a collection of reusable building
blocks.

Concepts:

 Objects: Represent real-world entities with attributes (data) and behaviors


(methods/functions).
 Classes: Act as blueprints for creating objects, defining their attributes and methods.
 Encapsulation: Combines data and related functions within objects, protecting data integrity
and promoting modularity.

Benefits:

 Improved Code Reusability: Classes enable creating reusable code templates for objects.
 Better Organization: OOP promotes a structured approach to program design, making large
projects easier to manage.
 Maintainability: Encapsulation protects data and keeps code organized, simplifying
maintenance.
3. Object-based and Object-oriented Design:

 Object-oriented language supports all the features of OOPs and Object-based language
doesn't support all the features of OOPs like Polymorphism and Inheritance.

4. C++ — Not Completely Object-oriented:

 C++ is not purely object-oriented; its design balances efficiency with object-oriented
principles.
 While C++ aligns closely with object-oriented philosophy, it's possible to write C++
programs without using object-oriented methodology.
 Object-oriented concepts like classes, encapsulation, inheritance, polymorphism, and code
reusability are essential in C++ programming.

Procedural Programming vs Object-Oriented Programming

Below are some of the differences between procedural and object-oriented


programming:

Procedural Oriented Programming Object-Oriented Programming

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


divided into small parts called functions. is divided into small parts called objects.

Procedural programming follows a top-down Object-oriented programming follows a


approach. bottom-up approach.

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


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

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


possible. programming.

Examples: C, FORTRAN, Pascal, Basic, Examples: C++, Java, Python, C#,


etc. etc.
C++ overview:

Include Variables,constants,datatypes and Features of OOPS also.

1.Introduction to C++ Programming Language


Write introduction (Refer Up)

2. Features of C++
 Object-Oriented Programming
 Machine Independent
 Simple
 High-Level Language
 Popular
 Case-sensitive
 Compiler Based
 Dynamic Memory Allocation
 Memory Management
 Multi-threading
3.History of C++:(give importance for heading)
Origins (1979):

 Bjarne Stroustrup, motivated by limitations of Simula (object-oriented language) for


practical use, began developing "C with Classes" as a Ph.D. thesis project.
 The goal was to integrate object-oriented features into C, a popular language known for
efficiency and portability.

Early Development (1979 - 1983):

 C with Classes compiler (Cfront) was created, translating C with Classes code to standard
C.
 Key features included inheritance, default arguments, classes, and inlining.
 Cfront was a self-hosting compiler, written mostly in C with Classes.
Language Maturation (1983 - 1989):

 The name changed to C++ (inspired by the increment operator ++).


 Significant features were added: virtual functions, operator overloading, references, and
single-line comments (//).

Commercialization and Standardization (1985 - 1998):

 Bjarne Stroustrup's book "The C++ Programming Language" was published, becoming a
key reference.
 C++ was commercialized but lacked formal standardization.
 The language was updated in 1989 to include protected and static members, and
multiple inheritance.
 The Annotated C++ Reference manual was released in 1990.

Standardization Era (1998 - Present):

 The first international standard, C++98 (ISO/IEC 14882:1998), was published in 1998.
 The Standard Template Library (STL) was incorporated.
 C++03 (2003) addressed issues identified in C++98.
 Technical reports (TR1, etc.) proposed new features leading to C++0x (informal name).
 C++11 (2011) was finally standardized after years of development. The Boost libraries
significantly influenced this standard.
 Key features introduced in C++11 include:
o New for loop syntax (like foreach loops)
o Standard threading library
o Variadic templates
o New smart pointers (unique_ptr, shared_ptr)
o New C++ time library, atomics support
o Regular expression support
o Improved union and array initialization
4. Interesting Facts about C++(study headings)

 Evolution from C: C++ was originally called "C with Classes" by its creator, Bjarne
Stroustrup, highlighting its roots in the C language but with added object-oriented features.
 Not purely object-oriented: Unlike Java, C++ strikes a balance between efficiency and
object-oriented features. You can write C++ programs without using object-oriented
concepts at all.
 Powerful for various domains: C++ is a versatile language used for system
programming (operating systems), game development, large-scale software applications,
and more.
 Influence on other languages: C++ has significantly influenced many other
programming languages, including Java, C#, and even newer versions of C.
 Standard Template Library (STL): C++ boasts a rich standard library (STL) offering pre-
written data structures and algorithms, saving programmers time and effort.
 Four memory management approaches: C++ provides flexibility with four memory
management models (automatic, static, dynamic, and thread storage), allowing for control
over memory usage.
 Widespread adoption: C++ remains a popular and relevant language, with a large
developer community and many resources available.
 Multiple inheritance: Unlike some object-oriented languages, C++ supports multiple
inheritance, allowing classes to inherit properties and methods from multiple parent
classes. This can be powerful but also complex to manage.
 Operator overloading: C++ allows programmers to redefine the behavior of operators
(like + or *) for custom classes, enabling intuitive use of these operators with objects.
5. Setting up a Local Environment
install two important software:
1. C++ Compiler
2. Text Editor
1. C++ Compiler
A compiler is a computer program that converts high-level language into
machine-understandable low-level language.
2. Text Editor

Text Editors are the type of programs used to edit or write texts. We will use
text editors to type our C++ programs. The normal extension of a text file is
(.txt) but a text file containing a C++ program should be saved with a ‘.cpp’
extension.
Similarities between C and C++ are:
 Both the languages have a similar syntax.
 Code structure of both the languages are same.
 The compilation of both the languages is similar.
 They share the same basic syntax. Nearly all of C’s operators and
keywords are also present in C++ and do the same thing.
 C++ has a slightly extended grammar than C, but the basic grammar
is the same.
 Basic memory model of both is very close to the hardware.
 Same notions of stack, heap, file-scope and static variables are
present in both the languages.
Differences between C and C++ are: (study any 4)

C-Based on Top down approach


C++- Based on Bottom up approach
C++ Variables:
 The value stored in a variable can be changed during program
execution.

How to Declare Variables?


// Declaring a single variable
type variable_name;

// Declaring multiple variables:


type variable1_name, variable2_name, variable3_name;
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.
Valid variable names:
int x; //can be letters
int _yz; //can be underscores
int z40;//can be letters
Invalid variable names:
int 89; Should not be a number
int a b; //Should not contain any whitespace
int double;// C++ keyword CAN NOT BE USED

Constants in C++
Constants in C++ refer to variables with fixed values that cannot be
changed.
Syntax:
const DATATYPE variable_name = value;
C++ Data Types
Data types specify the size and types of values to be stored.
3 Types:
1.Primitive Data Types:
Integer: The keyword used for integer data types is int. Integers typically
require 4 bytes of memory space.
Character: Character data type is used for storing characters.
require 1 byte of memory space.
Boolean: true or false.
void: Void means without any value.

// C++ Program to Demonstrate the correct size


// of various data types on your computer.
#include <iostream>
using namespace std;

int main()
{
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;

cout << "Size of long : " << sizeof(long) << endl;


cout << "Size of float : " << sizeof(float) << endl;

cout << "Size of double : " << sizeof(double) << endl;

return 0;
}
Output:
Size of char : 1
Size of int : 4
Size of long : 8
Size of float : 4
Size of double : 8

2. Derived Data Types: Derived data types that are derived from the
primitive or built-in datatypes are referred to as Derived Data Types. These
can be of four types namely:
 Function
 Array
 Pointer
 Reference
3. Abstract or User-Defined Data Types: Abstract or User-Defined data
types are defined by the user itself. Like, defining a class in C++ or a
structure. C++ provides the following user-defined datatypes:
 Class
 Structure
 Union
 Enumeration
 Typedef defined Datatype

First C++ Program:

// Your First C++ Program

#include <iostream>
using namespace std;

int main()
{
cout << "Hello World!";
return 0;
}

Line 1: #include <iostream>

 This line is a preprocessor directive, which instructs the compiler to include the contents of
the <iostream> header file.
 The <iostream> header file provides essential input/output functionalities in C++. It
contains definitions for objects like cout (used for console output) and cin (used for
console input).

Line 2: using namespace std;

 This line uses the using namespace std; directive.


 This statement tells the compiler to bring all the elements (functions, variables, etc.)
defined within the std namespace into the current scope. This means you can use objects
like cout without the std:: prefix.
 While convenient for small programs, using using namespace std; is generally
discouraged in larger projects. This is because different libraries or parts of your code
might define objects with the same name, leading to naming conflicts.

Line 4: int main()

 This line declares the main function, which is the entry point of the program.
 The int before main specifies that the function will return an integer value (0 in this case)
to indicate successful execution.
 In C++, every program execution begins from the main function.

Line 5: cout << "Hello World";

 This line is the core functionality of the program.


 cout is the standard output stream object from the iostream library. It's used to print data
to the console.
 The << operator is the insertion operator. It's used to send data (the string "Hello World" in
this case) to the output stream (cout).

Line 6: return 0;

 This line returns the value 0 from the main function.


 In C++, a non-zero return value from main often indicates an error during program
execution. Here, 0 signifies successful execution.

Name space:
a namespace is a declarative region that provides a way to organize code elements (functions, variables,
classes, etc.) and prevent naming conflicts.
C++ Basic Syntax:

1. Header File

we used the #include <iostream> statement to tell the compiler to


include an iostream header file library which stores the definition of the cin
and cout methods that we have used for input and output. #include is a
preprocessor directive using which we import header files.

Syntax:
#include <library_name>

2. Namespace

A namespace in C++ is used to provide a scope or a region where we define


identifiers. It is used to avoid name conflicts between two identifiers.
In line #2, we have used the using namespace std statement for
specifying that we will be the standard namespace where all the standard
library functions are defined.

Syntax:
using namespace std;
3. Main Function

Functions are basic building blocks of a C++ program that contains the
instructions for performing some specific task.
In line #3, we defined the main function as int main(). The main function is
the most important part of any C++ program. The program execution always
starts from the main function. All the other functions are called from the
main function. In C++, the main function is required to return some value
indicating the execution status.
Syntax:
int main() {

... code ....


return 0;
}

4. Blocks

Blocks are the group of statements that are enclosed within { } braces. They
define the scope of the identifiers and are generally used to enclose the body
of functions and control statements.
The body of the main function is from line #4 to line #9 enclosed within
{ }.
Syntax:
{

// Body of the Function

return 0;
}

5. Semicolons

As you may have noticed by now, each statement in the above code is
followed by a ( ; ) semicolon symbol. It is used to terminate each line of the
statement of the program. When the compiler sees this semicolon, it
terminates the operation of that line and moves to the next line.
Syntax:
any_statement ;

6. Identifiers

We use identifiers for the naming of variables, functions, and other user-
defined data types. An identifier may consist of uppercase and lowercase
alphabetical characters, underscore, and digits.
Example:
int num1 = 24;
int num2 = 34;
num1 & num2 are the identifiers and int is the data type.

7. Keywords

In the C++ programming language, there are some reserved words that
are used for some special meaning in the C++ program. It can’t be
used for identifiers.
For example, the words int, return, and using are some keywords used in
our program. These all have some predefined meaning in the C++ language.
There are total 95 keywords in C++. These are some keywords.
int void if while for
auto bool break

this static new true false


case char class

8. Basic Output cout

In line #7, we have used the cout method which is the basic output method
in C++ to output the sum of two numbers in the standard output stream
(stdout).

Syntax:
cout << result << endl;

// C++ program to demonstrate the basic syntax


// Header File Library
#include <iostream>

// Standard Namespace
using namespace std;

// Main Function
int main()
{

// Body of the Function

// Declaration of Variable
int num1 = 24;
int num2 = 34;
int result = num1 + num2;

// Output
cout << result << endl;

// Return Statement
return 0;
}

Output
58

C++ Comments:
Comments in C++ are meant to explain the code as well as to make it more
readable.
Types of Comments in C++
In C++ there are two types of comments :
 Single-line comment
 Multi-line comment
1. Single Line Comment
In C++ Single line comments are represented as // double forward slash. It
applies comments to a single line only. The compiler ignores any text after //
and it will not be executed.
Syntax:
// Single line comment

2. Multi-Line Comment
A multi-line comment can occupy many lines of code, it starts with /* and
ends with */, but it cannot be nested. Any text between /* and */ will be
ignored by the compiler.
Syntax:
/*
Multiline Comment
.
.
.
*/

Example:
#include <iostream>
using namespace std;

int main()
{
/* Multi line comment which
will be ignored by the compiler
*/
cout << "GFG!";
return 0;
}

C++ Tokens
In C++, tokens can be defined as the smallest building block of C++
programs that the compiler understands.
Types of Tokens in C++
1. Identifiers
2. Keywords
3. Constants
4. Strings
5. Special Symbols
6. Operators
1. Identifiers
In C++, entities like variables, functions, classes, or structs must be given
unique names within the program so that they can be uniquely identified.
The unique names given to these entities are known as identifiers.
In the below example, “first_name’ is an identifier.
string first_name = "Raju";

We have to follow a set of rules to define the name of identifiers as


follows:
1. An identifier can only begin with a letter or an underscore(_).
2. An identifier can consist of letters (A-Z or a-z), digits (0-9),
and underscores (_). White spaces and Special characters can not
be used as the name of an identifier.
3. Keywords cannot be used as an identifier because they are reserved
words to do specific tasks. For example, string, int, class, struct,
etc.
4. Identifier must be unique in its namespace.
5. As C++ is a case-sensitive language so identifiers such as
‘first_name’ and ‘First_name’ are different entities.
6. Here are some examples of valid and invalid identifiers in C++:
Valid
Identifiers Invalid Identifiers

#name (Cannot start with special character


_name
except ‘_’)

Number89 2num (Cannot start with a digit)


Valid
Identifiers Invalid Identifiers

first_name first name (Cannot include space)

_last_name
string (Cannot be same as a keyword)
_

2. Keywords
Keywords in C++ are the tokens that are the reserved words in programming
languages that have their specific meaning and functionalities within a
program.
Some of the main Keywords are:
catc cha cons continu
break try class
h r t e

defaul delet els frien


auto for float
t e e d

3. Constants
Constants are the tokens in C++ that are used to define variables at the time
of initialization and the assigned value cannot be changed after that.
Define Constants using the ‘const’ Keyword in C++
Syntax
const data_type variable_name = value;
4. Strings
In C++, a string is not a built-in data type like ‘int’, ‘char’, or ‘float’.
When we define any variable using the ‘string’ keyword we are actually
defining an object that represents a sequence of characters.
string variable_name = "This is string";

5. Special Symbols
Special symbols are the token characters having specific meanings within the
syntax of the programming language.
Below are the most common special symbols used in C++
programming:
 Semicolon (;): It is used to terminate the statement.
 Square brackets []: They are used to store array elements.
 Curly Braces {}: They are used to define blocks of code.
 Scope resolution (::): Scope resolution operator is used to access
members of namespaces, classes, etc.
 Dot (.): Dot operator also called member access operator used to
access class and struct members.
 Assignment operator ‘=’: This operator is used to assign values to
variables.
 Double-quote (“): It is used to enclose string literals.
 Single-quote (‘): It is used to enclose character literals.
6. Operators
C++ operators are special symbols that are used to perform operations on
operands such as variables, constants, or expressions.

Difference between Keyword and Identifier:

SR.
NO. KEYWORD IDENTIFIER

Keywords are predefined word Identifiers are the values used to


that gets reserved for working define different programming items
1 program that have special such as variables, integers,
meaning and cannot get used structures, unions and others and
anywhere else. mostly have an alphabetic character.

Identify the name of a particular


2 Specify the type/kind of entity.
entity.

It always starts with a First character can be a uppercase,


3
lowercase letter. lowercase letter or underscore.

A keyword should be in lower An identifier can be in upper case or


4
case. lower case.

An identifier can consist of


A keyword contains only
5 alphabetical characters, digits and
alphabetical characters.
underscores.

Writing First C++ Program – Hello World Example


// C++ program to display "Hello World"

// Header file for input output functions


#include <iostream>
using namespace std;

// Main() function: where the execution of


// program begins
int main()
{
// Prints hello world
cout << "Hello World";

return 0;
}

Output
Hello World

Line 1: #include <iostream>

 This line is a preprocessor directive, which instructs the compiler to include the contents of
the <iostream> header file.
 The <iostream> header file provides essential input/output functionalities in C++. It
contains definitions for objects like cout (used for console output) and cin (used for
console input).

Line 2: using namespace std;

 This line uses the using namespace std; directive.


 This statement tells the compiler to bring all the elements (functions, variables, etc.)
defined within the std namespace into the current scope. This means you can use objects
like cout without the std:: prefix.
 While convenient for small programs, using using namespace std; is generally
discouraged in larger projects. This is because different libraries or parts of your code
might define objects with the same name, leading to naming conflicts.

Line 4: int main()

 This line declares the main function, which is the entry point of the program.
 The int before main specifies that the function will return an integer value (0 in this case)
to indicate successful execution.
 In C++, every program execution begins from the main function.

Line 5: cout << "Hello World";

 This line is the core functionality of the program.


 cout is the standard output stream object from the iostream library. It's used to print data
to the console.
 The << operator is the insertion operator. It's used to send data (the string "Hello World" in
this case) to the output stream (cout).

Line 6: return 0;

 This line returns the value 0 from the main function.


 In C++, a non-zero return value from main often indicates an error during program
execution. Here, 0 signifies successful execution.
Object Oriented Programming Features/Principles:
Object-oriented programming aims to implement real-world entities .
The main aim of OOP is to bind together the data and the functions that
operate on them.

There are some basic concepts that act as the building blocks of OOPs i.e.
1. Class
2. Objects
3. Encapsulation
4. Abstraction
5. Polymorphism
6. Inheritance
7. Dynamic Binding
8. Message Passing
Class
 A Class is a user-defined data type that has data members and
member functions.
 Data members are the data variables and member functions are the
functions used to manipulate these variables together.
 We can say that a Class in C++ is a blueprint representing a group
of objects which shares some common properties and behaviors.
 class :Car
 data member :wheels, speed limits, and mileage
 member functions: brakes, increase speed

Object:
An Object is an instance of a Class. When a class is defined, no memory is
allocated but when it is instantiated (i.e. an object is created) memory is
allocated.
Encapsulation
Encapsulation is defined as binding together the data and the functions that
manipulate them.

Encapsulation also leads to data abstraction or data hiding.

Abstraction
Abstraction means displaying only essential information and hiding the
details.
 Abstraction using Classes: We can implement Abstraction in C++
using classes. The class helps us to group data members and
member functions using available access specifiers
 Abstraction in Header files: One more type of abstraction in C++
can be header files. For example, consider the pow() method present
in math.h header file. Whenever we need to calculate the power of a
number, we simply call the function pow() present in the math.h
header file and pass the numbers as arguments without knowing the
underlying algorithm according to which the function is actually
calculating the power of numbers.

Polymorphism
we can define polymorphism as the ability of a message to be displayed in
more than one form.It is achieved by,
 Operator Overloading: The process of making an operator exhibit
different behaviors in different instances is known as operator
overloading.Example:+ is used for addition.But in situations it is used
for string concatenation also.
 Function Overloading: Function overloading is using a single
function name to perform different types of tasks.

We can write the Addition Method with the same name having different
parameters, the concerned method will be called according to parameters.

Inheritance
The capability of a class to derive properties and characteristics from another
class is called Inheritance.
 Sub Class: The class that inherits properties from another class is
called Sub class or Derived Class.
 Super Class: The class whose properties are inherited by a sub-
class is called Base Class or Superclass.
 Reusability: Inheritance supports the concept of “reusability”, i.e.
when we want to create a new class and there is already a class that
includes some of the code that we want, we can derive our new class
from the existing class. By doing this, we are reusing the fields and
methods of the existing class.

Dynamic Binding
In dynamic binding, the code to be executed to the function call is decided at
runtime. In static binding the code to be executed to the function call is
decided at Compile time/Build time.

Message Passing
Objects communicate with one another by sending and receiving information.
Message passing involves specifying the name of the object, the name of the
function, and the information to be sent.

APPLICATION OF OOP:

1. Real – Time systems.


2. Simulation and modeling
3. Object oriented databases.
4. Hypertext,hypermedia and expertext.
5. Al and expert systems.
6. Neural networks and parallel programming.
7. Dicision support and office automation systems.
8. CIM / CAM / CAD system.

Classes and Objects:


A class is defined in C++ using the keyword class followed by the name of
the class. The body of the class is defined inside the curly brackets and
terminated by a semicolon at the end.

Declaring Objects
When a class is defined, only the specification for the object is defined; no
memory or storage is allocated. To use the data and access functions defined
in the class, you need to create objects.
Syntax
ClassName ObjectName;
Accessing data members and member functions: The data members
and member functions of the class can be accessed using the dot(‘.’)
operator with the object.

objectName.Functionname();

Accessing Data Members:


There are three access modifiers: public, private, and protected.
class Geeks
{
// Access specifier
public:
// Data Members
string geekname;
// Member Functions()
void printname()
{
cout << "Geekname is:" << geekname;
}
};

int main()
{
// Declare an object of class geeks
Geeks obj1;
// accessing data member
obj1.geekname = "Abhi";
// accessing member function
obj1.printname();
return 0;
}

Output
Geekname is:Abhi

Member Functions in Classes/Methods and Messages


There are 2 ways to define a member function:
 Inside class definition
 Outside class definition
Inside class definition:
class Geeks
{
// Access specifier
public:
// Data Members
string geekname;
// Member Functions()
void printname()
{
cout << "Geekname is:" << geekname;
}
};

int main()
{
// Declare an object of class geeks
Geeks obj1;
// accessing data member
obj1.geekname = "Abhi";
// accessing member function
obj1.printname();
return 0;
}

Outside class definition:

To define a member function outside the class definition we have to use


the scope resolution:: operator along with the class name and function
name.

return type class-name::function-name(argument declaration )


{
function-body
}

class Geeks
{
public:
string geekname;
int id;

// printname is not defined inside class definition


void printname();

// printid is defined inside class definition


void printid()
{
cout <<"Geek id is: "<<id;
}
};

// Definition of printname using scope resolution operator ::


void Geeks::printname()
{
cout <<"Geekname is: "<<geekname;
}
int main() {

Geeks obj1;
obj1.geekname = "xyz";
obj1.id=15;

// call printname()
obj1.printname();
cout << endl;

// call printid()
obj1.printid();
return 0;
}

Output
Geekname is: xyz
Geek id is: 15
}
};

Abstraction and encapsulation:

Encapsulation:
Encapsulation is defined as binding together the data and the
functions that manipulate them.
Consider a real-life example of encapsulation, in a company, there are
different sections like the accounts section, finance section, sales
section, etc. Now,
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.
Two Important property of Encapsulation

Data Protection: Encapsulation protects the internal state of an


object by keeping its data members private.
Information Hiding: Encapsulation hides the internal
implementation details of a class from external code.
Features:

The function which we are making inside the class must use only
member variables, only then it is called encapsulation.

#include <iostream>
using namespace std;

class Encapsulation {
private:
// Data hidden from outside world
int x;

public:
// Function to set value of
// variable x
void set(int a) { x = a; }

// Function to return value of


// variable x
int get() { return x; }
};

// Driver code
int main()
{
Encapsulation obj;
obj.set(5);
cout << obj.get();
return 0;
}

Output
5
Explanation: In the above program, the variable x is made private.
This variable can be accessed and manipulated only using the
functions get() and set() which are present inside the class. Thus we
can say that here, the variable x and the functions get() and set() are
bound together which is nothing but encapsulation.
Role of Access Specifiers in Encapsulation:
Private: Private access specifier means that the member

function or data member can only be accessed by other
member functions of the same class.
 Protected: A protected access specifier means that the
member function or data member can be accessed by other
member functions of the same class or by derived classes.
 Public: Public access specifier means that the member
function or data member can be accessed by any code.
By default, all data members and member functions of a class are
made private by the compiler.

Abstraction:

Abstraction means displaying only essential information and hiding


the details.
Types of Abstraction:
1. Data abstraction – This type only shows the required
information about the data and hides the unnecessary data.
2. Control Abstraction – This type only shows the required
information about the implementation and hides unnecessary
information.

Abstraction in Header files


One more type of abstraction in C++ can be header files. For
example, consider the pow() method present in math.h header file.
Whenever we need to calculate the power of a number, we simply call
the function pow() present in the math.h header file and pass the
numbers as arguments without knowing the underlying algorithm
according to which the function is actually calculating the power of
numbers.
Abstraction using Access Specifiers
Members declared as public in a class can be accessed from

anywhere in the program.
 Members declared as private in a class, can be accessed
only from within the class.
Example:
 C++
// C++ Program to Demonstrate the
// working of Abstraction
#include <iostream>
using namespace std;

class implementAbstraction {
private:
int a, b;

public:
// method to set values of
// private members
void set(int x, int y)
{
a = x;
b = y;
}

void display()
{
cout << "a = " << a << endl;
cout << "b = " << b << endl;
}
};

int main()
{
implementAbstraction obj;
obj.set(10, 20);
obj.display();
return 0;
}

Output
a = 10
b = 20
You can see in the above program we are not allowed to access the
variables a and b directly, however, one can call the function set() to
set the values in a and b and the function display() to display the
values of a and b.
 Difference between Abstraction and Encapsulation in C++

https://www.geeksforgeeks.org/difference-between-abstraction-and-encapsulation-in-c/

Inheritance in C++
The capability of a class to derive properties and characteristics from
another class is called Inheritance. Inheritance is one of the most
important features of Object-Oriented Programming.
Inheritance is a feature or a process in which, new classes are created
from the existing classes. The new class created is called “derived
class” or “child class” and the existing class is known as the “base
class” or “parent class”. The derived class now is said to be inherited
from the base class.
 Sub Class: The class that inherits properties from another
class is called Subclass or Derived Class.
 Super Class: The class whose properties are inherited by a
subclass is called Base Class or Superclass.
 Implementing inheritance in C++: For creating a sub-class
that is inherited from the base class we have to follow the below
syntax.
 Derived Classes: A Derived class is defined as the class
derived from the base class.
Syntax:
 class <derived_class_name> : <access-specifier>
<base_class_name>
{
//body
}
 Where
class — keyword to create a new class
derived_class_name — name of the new class, which will inherit
the base class
access-specifier — either of private, public or protected. If
neither is specified, PRIVATE is taken as default
base-class-name — name of the base class
Note: A derived class doesn’t inherit access to private data
members. However, it does inherit a full parent object, which
contains any private members which that class declares.
 Example:
1. class ABC : private XYZ //private derivation
{ }
2. class ABC : public XYZ //public derivation
{ }
3. class ABC : protected XYZ //protected derivation
{ }
4. class ABC: XYZ //private derivation by
default
{ }
Note:
o When a base class is privately inherited by the derived class, public
members of the base class becomes the private members of the
derived class and therefore, the public members of the base class can
only be accessed by the member functions of the derived class. They
are inaccessible to the objects of the derived class.
o On the other hand, when the base class is publicly inherited by the
derived class, public members of the base class also become the
public members of the derived class. Therefore, the public members
of the base class are accessible by the objects of the derived class as
well as by the member functions of the derived class.
Example1

#include <iostream>

// Base class
class Animal
{
public:
void eat()
{
std::cout << "Animal is eating...\n";
}

void sleep() {
std::cout << "Animal is sleeping...\n";
}
};

// Derived class inheriting from Animal


class Dog : public Animal {
public:
void bark() {
std::cout << "Dog is barking...\n";
}
};

int main() {
// Create an object of Dog
Dog dog;

// Accessing inherited member functions


dog.eat(); // Output: Animal is eating...
dog.sleep(); // Output: Animal is sleeping...

// Accessing member function of derived class


dog.bark(); // Output: Dog is barking...

return 0;
}

// Example 2: define member function without argument within


// the class

#include <iostream>
using namespace std;

class Person {
int id;
char name[100];

public:
void set_p()
{
cout << "Enter the Id:";
cin >> id;
cout << "Enter the Name:";
cin >> name;
}

void display_p()
{
cout << endl <<"Id: "<< id << "\nName: " << name <<endl;
}
};

class Student : private Person {


char course[50];
int fee;

public:
void set_s()
{
set_p();
cout << "Enter the Course Name:";
cin >> course;
cout << "Enter the Course Fee:";
cin >> fee;
}

void display_s()
{
display_p();
cout <<"Course: "<< course << "\nFee: " << fee << endl;
}
};

int main()
{
Student s;
s.set_s();
s.display_s();
return 0;
}
Output:
Enter the Id: 101
Enter the Name: Dev
Enter the Course Name: GCS
Enter the Course Fee:70000

Id: 101
Name: Dev
Course: GCS
Fee: 70000

C++ 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.
Types of Polymorphism
 Compile-time Polymorphism
 Runtime Polymorphism

1. Compile-Time Polymorphism
This type of polymorphism is achieved by function overloading or
operator overloading.
A. Function Overloading
When there are multiple functions with the same name but different
parameters, then the functions are said to be overloaded, hence this
is known as Function Overloading. Functions can be overloaded
by changing the number of arguments or/and changing the
type of arguments.

Example:
// C++ program to demonstrate
// function overloading or
// Compile-time Polymorphism
#include <bits/stdc++.h>
using namespace std;
class fn
{
public:
// Function with 1 int parameter
void func(int x)
{
cout << "value of x is " << x << endl;
}

// Function with same name but


// 1 double parameter
void func(double x)
{
cout << "value of x is " << x << endl;
}

// Function with same name and


// 2 int parameters
void func(int x, int y)
{
cout << "value of x and y is " << x << ", " << y
<< endl;
}
};

// Driver code
int main()
{
fn obj1;

// Function being called depends


// on the parameters passed
// func() is called with int value
obj1.func(7);

// func() is called with double value


obj1.func(9.132);

// func() is called with 2 int values


obj1.func(85, 64);
return 0;
}

Output
value of x is 7
value of x is 9.132
value of x and y is 85, 64

Explanation: In the above example, a single function named


function func() acts differently in three different situations, which is a
property of polymorphism.

B. Operator Overloading
C++ has the ability to provide the operators with a special meaning
for a data type, this ability is known as operator overloading. For
example, we can make use of the addition operator (+) for string
class to concatenate two strings. We know that the task of this
operator is to add two operands. So a single operator ‘+’, when
placed between integer operands, adds them and when placed
between string operands, concatenates them.
Example:

// C++ program to demonstrate


// Operator Overloading or
// Compile-Time Polymorphism
#include <iostream>
using namespace std;

class Complex {
private:
int real, imag;

public:
Complex(int r = 0, int i = 0)
{
real = r;
imag = i;
}

// This is automatically called


// when '+' is used with between
// two Complex objects
Complex operator+(Complex const& obj)
{
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" << imag << endl; }
};

// Driver code
int main()
{
Complex c1(10, 5), c2(2, 4);

// An example call to "operator+"


Complex c3 = c1 + c2;
c3.print();
}
Output
12 + i9
Explanation: In the above example, the operator ‘+’ is overloaded. Usually, this operator
is used to add two numbers (integers or floating point numbers), but here the operator is
made to perform the addition of two imaginary or complex numbers.
2. Runtime Polymorphism
This type of polymorphism is achieved by Function Overriding. Late
binding and dynamic polymorphism are other names for runtime
polymorphism.
A. Function Overriding
Function Overriding occurs when a derived class has a definition for
one of the member functions of the base class. That base function is
said to be overridden.

Here, the same function print() is defined in both Base and Derived classes.

So, when we call print() from the Derived object d, the print() from Derived is executed by
overriding the function in Base.

Access Overridden Function in C++:

To access the overridden function of the base class, we use the scope resolution
operator :: .

// C++ program to access overridden function


// in main() using the scope resolution operator ::

#include <iostream>
using namespace std;

class Base
{
public:
void print()
{
cout << "Base Function" << endl;
}
};

class Derived : public Base {


public:
void print()
{
cout << "Derived Function" << endl;
}
};

int main()
{
Derived d1, d2;
d1.print();

// access print() function of the Base class


d2.Base::print();

return 0;
}

Output

Derived Function
Base Function

Here, this statement

derived2.Base::print();

accesses the print() function of the Base class.

B.Virtual Function
A virtual function is a member function that is declared in the base
class using the keyword virtual and is re-defined (Overridden) in the
derived class.
Some Key Points About Virtual Functions:
Virtual functions are Dynamic in nature.

 They are defined by inserting the keyword “virtual” inside a
base class and are always declared with a base class and
overridden in a child class
 A virtual function is called during Runtime.
Example:

#include <iostream>
using namespace std;

class Base
{
public:
virtual void print()
{
cout << "Base Function" << endl;
}
};

class Derived : public Base


{
public:
void print()
{
cout << "Derived Function" << endl;
}
};

int main()
{
Derived d1;

// pointer of Base type that points to derived1


Base * base1 = &d1;

// calls member function of Derived class


base1->print();

return 0;
}

Output

Derived Function
C++ Pure Virtual Functions

Pure virtual functions are used


 if a function doesn't have any use in the base class
 but the function must be implemented by all its derived classes

Let's take an example,


Suppose, we have derived Triangle, Square and Circle classes from the Shape class, and we
want to calculate the area of all these shapes.

In this case, we can create a pure virtual function named calculateArea() in the Shape. Since it's
a pure virtual function, all derived classes Triangle, Square and Circle must include
the calculateArea() function with implementation.

A pure virtual function doesn't have the function body and it must end with = 0. For example,

class Shape {
public:

// creating a pure virtual function


virtual void calculateArea() = 0;
};

Note: The = 0 syntax doesn't mean we are assigning 0 to the function. It's just the way we
define pure virtual functions.

Abstract class:
A class that contains a pure virtual function is known as an abstract class. In
the above example, the class Shape is an abstract class.
// C++ program to calculate the area of a square and a circle

#include <iostream>
using namespace std;

// Abstract class
class Shape
{
protected:
float dimension;

public:
void getDimension()
{
cin >> dimension;
}

// pure virtual Function


virtual float calculateArea() = 0;
};

// Derived class
class Square : public Shape {
public:
float calculateArea() {
return dimension * dimension;
}
};

// Derived class
class Circle : public Shape {
public:
float calculateArea() {
return 3.14 * dimension * dimension;
}
};

int main() {
Square square;
Circle circle;

cout << "Enter the length of the square: ";


square.getDimension();
cout << "Area of square: " << square.calculateArea() << endl;

cout << "\nEnter radius of the circle: ";


circle.getDimension();
cout << "Area of circle: " << circle.calculateArea() << endl;

return 0;
}

Output

Enter the length of the square: 4


Area of square: 16

Enter radius of the circle: 5


Area of circle: 78.5

In this program, virtual float calculateArea() = 0; inside the Shape class is a pure virtual function.

That's why we must provide the implementation of calculateArea() in both of our derived
classes, or else we will get an error.

You might also like