Module1 C++
Module1 C++
Module1 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.
Concepts:
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.
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.
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.
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):
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):
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.
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)
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.
int main()
{
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << 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
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World!";
return 0;
}
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).
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 6: return 0;
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
Syntax:
#include <library_name>
2. Namespace
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() {
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:
{
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
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;
// Standard Namespace
using namespace std;
// Main Function
int main()
{
// 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";
_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
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.
SR.
NO. KEYWORD IDENTIFIER
return 0;
}
Output
Hello World
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).
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 6: return 0;
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.
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:
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();
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
int main()
{
// Declare an object of class geeks
Geeks obj1;
// accessing data member
obj1.geekname = "Abhi";
// accessing member function
obj1.printname();
return 0;
}
class Geeks
{
public:
string geekname;
int id;
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
}
};
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
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; }
// 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:
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";
}
};
int main() {
// Create an object of Dog
Dog dog;
return 0;
}
#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;
}
};
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;
}
// Driver code
int main()
{
fn obj1;
Output
value of x is 7
value of x is 9.132
value of x and y is 85, 64
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:
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i = 0)
{
real = r;
imag = i;
}
// Driver code
int main()
{
Complex c1(10, 5), c2(2, 4);
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.
To access the overridden function of the base class, we use the scope resolution
operator :: .
#include <iostream>
using namespace std;
class Base
{
public:
void print()
{
cout << "Base Function" << endl;
}
};
int main()
{
Derived d1, d2;
d1.print();
return 0;
}
Output
Derived Function
Base Function
derived2.Base::print();
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;
}
};
int main()
{
Derived d1;
return 0;
}
Output
Derived Function
C++ Pure Virtual Functions
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:
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;
}
// 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;
return 0;
}
Output
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.