0% found this document useful (0 votes)
19 views53 pages

CPP Assignment

The document outlines the practical examination details for B.C.A (H) Semester III, focusing on programming in C++. It provides an overview of C++ as an object-oriented programming language, its features, basic data types, user-defined data types, functions, pointers, and various operators. Additionally, it includes example programs demonstrating the use of arithmetic, relational, logical, and bitwise operators.

Uploaded by

sibamdutta32
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views53 pages

CPP Assignment

The document outlines the practical examination details for B.C.A (H) Semester III, focusing on programming in C++. It provides an overview of C++ as an object-oriented programming language, its features, basic data types, user-defined data types, functions, pointers, and various operators. Additionally, it includes example programs demonstrating the use of arithmetic, relational, logical, and bitwise operators.

Uploaded by

sibamdutta32
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 53

B.C.

A (H) SEMESTER - III PRACTICAL


EXAMINATION-2024

PAPER : SOFTWARE LAB - IV

PAPER CODE : BCA 306

SUBJECT : PROGRAMMING IN
C++

NAME : SIBAM DUTTA

ROLL NO. : 221771120052

REGISTRATION NO. : 202205001515 of


2022-23

1
CHANDANNAGAR INSTITUTE
OF
MANAGEMENT &
TECHNOLOGY
OBJECT-ORIENTED
PROGRAMMING WITH
C++
Let’s discuss first that what is C++.
C++ is an object-oriented programming language. It was developed
by Bjarne Stroustrup at AT&T Bell Laboratories in Murray Hill, New Jersey,
USA, in the early 1980’s. Stroustrup an admirer of Simula67 and a strong
supporter of C, wanted to combine the best of both the languages and
create a more powerful language that could support object-oriented
programming features and still retain the power and elegance of C. The
result was C++. Therefore, C++ is an extension of C with a major addition
of the class construct feature of Simula67. Since the class was a major
addition to the original C language. Stroustrup initially called the new
language ‘C with Classes’. However, later in 1983, the name was changed
to C++. The idea of C++ comes from the C increment operator ++,
thereby suggesting that C++ is an augmented (incremented) version of C.
The most important facilities that C++ adds on to C are classes,
inheritance, function overloading, and operator overloading. These
features enable creating of abstract data types, inherit properties from
existing data types and supports polymorphism, thereby making C++ a
truly object-oriented language.
The object-oriented features in C++ allow programmers to build
large programs with clarity, extensibility and ease of maintenance,
incorporating the spirit and efficiency of C. The addition of new features
has transformed C from a language that currently facilitates top-down,
structured design, to one that provides bottom-up, object-oriented design.

2
 Example of C++ program:

#include<iostream> // include header file

using namespace std;

int main ()

cout<<"Hello World";

return 0;

// End of example

Basic Data types:-

Both C and C++ compilers support all the built in (also known as basic or fundamental)
Data types. With the exception of Void, the basic data types may have several modifiers
preceding them to serve the needs of various situations. The modifiers signed, unsigned,
long, and short may be applied to character and integer basic data types. However, the
modifiers longed may also be applied to double. Data type representation is machine
specific in C++. The given table lists all combinations of the basic data types and
modifiers along with their size and range for a 16 bit word machine.

Size and Range of C++ Basic Data types

Type Bytes Range


Char 1 -128 to 127

Unsigned char 1 0 to 255


Signed char 1 -128 to 127

Int 2 -32768 to 32767


Unsigned int 2 0 to 65535
Signed int 2 -31768 to 32767

Short int 2 -31768 to 32767


Unsigned short int 2 0 to 65535

Signed short int 2 -32768 to 32767


Long int 4 -2147483648 to
2147483647
Signed long int 4 -2147483648 to
2147483647
Unsigned long int 4 0 to 4294967295

3
Float 4 3.4E-38 to 3.4E+38

Double 8 1.7E-308 to 1.7E+308


Long double 10 3.4E-4932 to 1.1E+4932

User Defined Data types:-

Structures and classes:-

We have used user-defined data types such as “struct” and “Union” in C.


While these data types are legal in C++, some more features have been added to make
them suitable for object-oriented programming. C++ also permits us to define another
user define data type known as class which can be user just like any other basic data
type, to declare variables. The class variables are known as object, which are the central
focus of object-oriented programming.

Enumerated Data type:-

An Enumerated data type is another user defined type which provides a


way for attaching names to numbers, thereby increasing comprehensibility of the code.
The “Enum” keyword automatically enumerates a list of words by assigning them values
0,1,2, and so on. This facility provides an alternative means for creating symbolic
constants. The syntax of an “Enum” statement is similar to that of the struct statement.
Examples-

Enum shape{circle, square, triangle};

Enum colour{red, blue, green, yellow};

Enum position{off, on};

Derived data types:-

Arrays:-The applications of arrays in C++ is similar to that in C. The only


exception is the way character arrays are initialized. when initializing a character array in
ANSI C, the compiler will allow us to declare the array size as the exact length of the
string constant. For instance,

Char string[3]=”xyz”;

Is valid in ANSI C. It assumes that the programmer intends to leave out the null character
\0 in the definition. But in C++, the size should be one larger than the number of
characters in the string,

Char,string[4]=”xyz”; //o.k. for C++

Functions:- Functions have undergone major changes in C++. While some of


these changes are simple, others require a new way of thinking when organizing our
programs. Many of these modifications and improvements were driven by the
requirements of the object-oriented concept of C++. Some of these were introduced to
make the C++ program more reliable and readable.

Pointers:-

Pointers are symbolic representations of addresses. They enable programs to simulate


call-by-reference as well as to create and manipulate dynamic data structures. Iterating
over elements in arrays or other data structures is one of the main use of pointers.

4
The address of the variable you’re working with is assigned to the pointer variable that
points to the same data type (such as an int or string).
Syntax:
datatype *var_name;
int *ptr; // ptr can point to an address which holds int data

Operators in C++:-
Pointers are symbolic representations of addresses. They enable programs to simulate
call-by-reference as well as to create and manipulate dynamic data structures. Iterating
over elements in arrays or other data structures is one of the main use of pointers.
The address of the variable you’re working with is assigned to the pointer variable that
points to the same data type (such as an int or string).
Syntax:
datatype *var_name;
int *ptr; // ptr can point to an address which holds int data

1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Ternary or Conditional Operators

1) Arithmetic Operators

These operators are used to perform arithmetic or mathematical operations on the


operands. For example, ‘+’ is used for addition, ‘-‘ is used for subtraction ‘*’ is used for
multiplication, etc.
Arithmetic Operators can be classified into 2 Types:
A) Unary Operators: These operators operate or work with a single operand. For
example: Increment(++) and Decrement(--) Operators.

Sym
Name bol Description Example

int a = 5;
Increment Increases the integer value of
++ a++; //
Operator the variable by one
returns 6

int a = 5;
Decrement Decreases the integer value of
-- a--; //
Operator the variable by one
returns 4

5
Example:
the description
………………………………………………………………………………….
a++ is 10
++a is 12
b-- is 15
--b is 13
Time Complexity: O(1)
Auxiliary Space : O(1)

Note: ++a and a++, both are increment operators, however, both are slightly
different.
In ++a, the value of the variable is incremented first and then It is used in the
program. In a++, the value of the variable is assigned first and then It is incremented.
Similarly happens for the decrement operator.

B) Binary Operators: These operators operate or work with two operands. For
example: Addition(+), Subtraction(-), etc.

Sym
Name bol Description Example

int a = 3, b
= 6;
Addition + Adds two operands
int c = a+b;
// c = 9

int a = 9, b
= 6;
Subtracts second operand
Subtraction –
from the first int c = a-
b; // c = 3

int a = 3, b
= 6;
Multiplicati
* Multiplies two operands int c =
on
a*b; // c =
18

Division / Divides first operand by the int a = 12,


second operand b = 6;
int c =

6
Sym
Name bol Description Example

a/b; // c = 2

int a = 8, b
= 6;
Modulo Returns the remainder an
%
Operation integer division int c = a%b;
// c = 2

// CPP Program to demonstrate the Binary Operators

#include <iostream>

using namespace std;

int main()

int a = 8, b = 3;

// Addition operator

cout << "a + b = " << (a + b) << endl;

// Subtraction operator

cout << "a - b = " << (a - b) << endl;

// Multiplication operator

cout << "a * b = " << (a * b) << endl;

// Division operator

cout << "a / b = " << (a / b) << endl;

// Modulo operator

cout << "a % b = " << (a % b) << endl;

return 0;

7
Output
a + b = 11
a-b=5
a * b = 24
a/b=2
a%b=2
Time Complexity: O(1)
Auxiliary Space : O(1)

2) Relational Operators

These operators are used for the comparison of the values of two operands. For
example, ‘>’ checks if one operand is greater than the other operand or not, etc. The
result returns a Boolean value, i.e., true or false.
Sym
Name bol Description Example

int a = 3,
b = 6;
Is Equal To == Checks if both operands are equal a==b;
// returns
false

int a = 3,
b = 6;
Checks if first operand is greater than the
Greater Than > a>b;
second operand
// returns
false

int a = 3,
b = 6;
Greater Than or Checks if first operand is greater than or
>= a>=b;
Equal To equal to the second operand
// returns
false

int a = 3,
b = 6;
Checks if first operand is lesser than the
Less Than < a<b;
second operand
// returns
true

8
Sym
Name bol Description Example

int a = 3,
b = 6;
Less Than or Checks if first operand is lesser than or equal
<= a<=b;
Equal To to the second operand
// returns
true

int a = 3,
b = 6;
Not Equal To != Checks if both operands are not equal a!=b;
// returns
true

Example:

// CPP Program to demonstrate the Relational Operators

#include <iostream>

using namespace std;

int main()

int a = 6, b = 4;

// Equal to operator

cout << "a == b is " << (a == b) << endl;

// Greater than operator

cout << "a > b is " << (a > b) << endl;

// Greater than or Equal to operator

cout << "a >= b is " << (a >= b) << endl;

9
// Lesser than operator

cout << "a < b is " << (a < b) << endl;

// Lesser than or Equal to operator

cout << "a <= b is " << (a <= b) << endl;

// true

cout << "a != b is " << (a != b) << endl;

return 0;
}

Output

a == b is 0
a > b is 1
a >= b is 1
a < b is 0
a <= b is 0
a != b is 1
Time Complexity: O(1)
Auxiliary Space : O(1)
Here, 0 denotes false and 1 denotes true. To read more about this, please refer to the
article – Relational Operators.

3) Logical Operators

These operators are used to combine two or more conditions or constraints or to


complement the evaluation of the original condition in consideration. The result returns
a Boolean value, i.e., true or false.
Sym
Name bol Description Example

Logical && Returns true only if all the operands int a = 3,


AND are true or non-zero b = 6;
a&&b;
// returns

10
Sym
Name bol Description Example

true

int a = 3,
b = 6;
Logical Returns true if either of the operands
|| a||b;
OR is true or non-zero
// returns
true

int a = 3;
Logical Returns true if the operand is false or !a;
!
NOT zero
// returns
false

Example:

// CPP Program to demonstrate the Logical Operators

#include <iostream>

using namespace std;

int main()

int a = 6, b = 4;

// Logical AND operator

cout << "a && b is " << (a && b) << endl;

// Logical OR operator

cout << "a ! b is " << (a > b) << endl;

// Logical NOT operator

11
cout << "!b is " << (!b) << endl;

return 0;
}

Output

a && b is 1
a ! b is 1
!b is 0
Time Complexity: O(1)
Auxiliary Space : O(1)
Here, 0 denotes false and 1 denotes true. To read more about this, please refer to the
article – Logical Operators.
4) Bitwise Operators
These operators are used to perform bit-level operations on the operands. The
operators are first converted to bit-level and then the calculation is performed on the
operands. Mathematical operations such as addition, subtraction, multiplication, etc.
can be performed at the bit level for faster processing.

Sym
Name bol Description Example

int a = 2,
Copies a bit to the evaluated result if it exists in b = 3;
Binary AND &
both operands (a & b);
//returns 2

int a = 2,
Copies a bit to the evaluated result if it exists in b = 3;
Binary OR |
any of the operand (a | b);
//returns 3

int a = 2,
Copies the bit to the evaluated result if it is b = 3;
Binary XOR ^
present in either of the operands but not both (a ^ b);
//returns 1

int a = 2,
b = 3;
Shifts the value to left by the number of bits
Left Shift << (a <<
specified by the right operand.
1);
//returns 4

12
Sym
Name bol Description Example

int a = 2,
b = 3;
Shifts the value to right by the number of bits
Right Shift >> (a >>
specified by the right operand.
1);
//returns 1

One’s int b = 3;
Compleme ~ Changes binary digits 1 to 0 and 0 to 1 (~b);
nt //returns -4

Note: Only char and int data types can be used with Bitwise Operators.
Example:

// CPP Program to demonstrate the Bitwise Operators

#include <iostream>

using namespace std;

int main()

int a = 6, b = 4;

// Binary AND operator

cout << "a & b is " << (a & b) << endl;

// Binary OR operator

cout << "a | b is " << (a | b) << endl;

// Binary XOR operator

cout << "a ^ b is " << (a ^ b) << endl;

13
// Left Shift operator

cout << "a<<1 is " << (a << 1) << endl;

// Right Shift operator

cout << "a>>1 is " << (a >> 1) << endl;

// One’s Complement operator

cout << "~(a) is " << ~(a) << endl;

return 0;
}

Output

a & b is 4
a | b is 6
a ^ b is 2
a<<1 is 12
a>>1 is 3
~(a) is -7
Time Complexity: O(1)
Auxiliary Space : O(1)
To read more about this, please refer to the article – Bitwise Operators.

5) Assignment Operators

These operators are used to assign value to a variable. The left side operand of the
assignment operator is a variable and the right side operand of the assignment
operator is a value. The value on the right side must be of the same data type as the
variable on the left side otherwise the compiler will raise an error.

Sym Exam
Namemultiply bol Description ple

int a =
Assignment Assigns the value on the right to the variable on 2;
=
Operator the left
// a = 2

14
Sym Exam
Namemultiply bol Description ple

int a =
Add and First adds the current value of the variable on 2, b =
Assignment += left to the value on the right and then assigns 4;
Operator the result to the variable on the left a+=b;
// a = 6

int a =
2, b =
Subtract and First subtracts the value on the right from the 4;
-
Assignment current value of the variable on left and then
= a-
Operator assign the result to the variable on the left
=b; // a
= -2

int a =
Multiply and First multiplies the current value of the variable 2, b =
Assignment *= on left to the value on the right and then assign 4;
Operator the result to the variable on the left a*=b; /
/a=8

int a =
4, b =
Divide and First divides the current value of the variable on 2;
Assignment /= left by the value on the right and then assign
Operator the result to the variable on the left a
/=b; //
a=2

Example:

// CPP Program to demonstrate the Assignment Operators

#include <iostream>

using namespace std;

int main()

int a = 6, b = 4;

15
// Assignment Operator

cout << "a = " << a << endl;

// Add and Assignment Operator

cout << "a += b is " << (a += b) << endl;

// Subtract and Assignment Operator

cout << "a -= b is " << (a -= b) << endl;

// Multiply and Assignment Operator

cout << "a *= b is " << (a *= b) << endl;

// Divide and Assignment Operator

cout << "a /= b is " << (a /= b) << endl;

return 0;
}
Output

a=6
a += b is 10
a -= b is 6
a *= b is 24
a /= b is 6
Time Complexity: O(1)
Auxiliary Space : O(1)

6) Ternary or Conditional Operators(?:)

This operator returns the value based on the condition.


Expression1? Expression2: Expression3
The ternary operator ? determines the answer on the basis of the evaluation
of Expression1. If it is true, then Expression2 gets evaluated and is used as the
answer for the expression. If Expression1 is false, then Expression3 gets evaluated
and is used as the answer for the expression.
This operator takes three operands, therefore it is known as a Ternary Operator.

16
Example:

// CPP Program to demonstrate the Conditional Operators

#include <iostream>

using namespace std;

int main()

int a = 3, b = 4;

// Conditional Operator

int result = (a < b) ? b : a;

cout << "The greatest number is " << result << endl;

return 0;
}

Output
The greatest number is 4
Time Complexity: O(1)
Auxiliary Space : O(1)
7) There are some other common operators available in C++ besides the operators
discussed above. Following is a list of these operators discussed in detail:
A) sizeof Operator: This unary operator is used to compute the size of its operand or
variable.
sizeof(char); // returns 1
B) Comma Operator(,): This binary operator (represented by the token) is used to
evaluate its first operand and discards the result, it then evaluates the second operand
and returns this value (and type). It is used to combine various expressions together.
int a = 6;
int b = (a+1, a-2, a+5); // b = 11
C) -> Operator: This operator is used to access the variables of classes or structures.
cout<<emp->first_name;
D) Cast Operator: This unary operator is used to convert one data type into another.
float a = 11.567;
int c = (int) a; // returns 11
E) Dot Operator(.): This operator is used to access members of structure variables or
class objects in C++.
cout<<emp.first_name;
F) & Operator: This is a pointer operator and is used to represent the memory
address of an operand.
G) * Operator: This is an Indirection Operator

// CPP Program to demonstrate the & and * Operators

17
#include <iostream>
using namespace std;

int main()
{
int a = 6;
int* b;
int c;
// & Operator
b = &a;

// * Operator
c = *b;
cout << " a = " << a << endl;
cout << " b = " << b << endl;
cout << " c = " << c << endl;

return 0;
}

Output
a=6
b = 0x7ffe8e8681bc
c=6
H) << Operator: It is called the insertion operator. It is used with cout to print the
output.
I) >> Operator: It is called the extraction operator. It is used with cin to get the input.
int a;
cin>>a;
cout<<a;
Time Complexity: O(1)
Auxiliary Space : O(1)

Operator Precedence Chart

Preced Oper Associ


ence ator Description ativity

1. left-to-
() Parentheses (function call)
right

[] Brackets (array subscript)

. Member selection via object


name

18
Preced Oper Associ
ence ator Description ativity

-> Member selection via a pointer

++/– Postfix increment/decrement

right-to-
++/– Prefix increment/decrement
left

+/- Unary plus/minus

Logical negation/bitwise
!~
complement

2. (type Cast (convert value to


) temporary value of type)

* Dereference

& Address (of operand)

Determine size in bytes on this


sizeof
implementation

left-to-
3. *,/,% Multiplication/division/modulus
right

left-to-
4. +/- Addition/subtraction
right

<< , Bitwise shift left, Bitwise shift left-to-


5.
>> right right

<, Relational less than/less than left-to-


<= or equal to right
6.
>, Relational greater than/greater left-to-
>= than or equal to right

== , Relational is equal to/is not left-to-


7.
!= equal to right

left-to-
8. & Bitwise AND
right

19
Preced Oper Associ
ence ator Description ativity

left-to-
9. ^ Bitwise exclusive OR
right

left-to-
10. | Bitwise inclusive OR
right

left-to-
11. && Logical AND
right

left-to-
12. || Logical OR
right

right-to-
13. ?: Ternary conditional
left

right-to-
= Assignment
left

+= , Addition/subtraction
-= assignment

*= , / Multiplication/division
= assignment
14.
%= , Modulus/bitwise AND
&= assignment

^= , Bitwise exclusive/inclusive OR
|= assignment

Bitwise shift left/right


<>=
assignment

left-to-
15. , expression separator
right

C++ Classes and Objects



Class in C++ is the building block that leads to Object-Oriented programming. It is a


user-defined data type, which holds its own data members and member functions, which
can be accessed and used by creating an instance of that class. A C++ class is like a

20
blueprint for an object. For Example: Consider the Class of Cars. There may be many
cars with different names and brands but all of them will share some common properties
like all of them will have 4 wheels, Speed Limit, Mileage range, etc. So here, Car is the
class, and wheels, speed limits, and mileage are their properties.
 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, these data members and
member functions define the properties and behavior of the objects in a Class.
 In the above example of class Car, the data member will be speed
limit, mileage, etc, and member functions can be applying brakes, increasing
speed, etc.
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.
Defining Class and Declaring 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. For example, if the name of the object is obj and you want to
access the member function with the name printName() then you will have to
write obj.printName().
Accessing Data Members
The public data members are also accessed in the same way given however the private
data members are not allowed to be accessed directly by the object. Accessing a data
member depends solely on the access control of that data member. This access control is
given by Access modifiers in C++. There are three access modifiers: public, private,
and protected.

21
// C++ program to demonstrate accessing of data members

#include <bits/stdc++.h>

using namespace std;

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


There are 2 ways to define a member function:
 Inside class definition
 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.

// C++ program to demonstrate function

22
// declaration outside class

#include <bits/stdc++.h>

using namespace std;

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

23
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

Note that all the member functions defined inside the class definition are by
default inline, but you can also make any non-class function inline by using the
keyword inline with them. Inline functions are actual functions, which are copied
everywhere during compilation, like pre-processor macro, so the overhead of function
calls is reduced.
Note: Declaring a friend function is a way to give private access to a non-member
function.

Note that all the member functions defined inside the class definition are by
default inline, but you can also make any non-class function inline by using the
keyword inline with them. Inline functions are actual functions, which are copied
everywhere during compilation, like pre-processor macro, so the overhead of function
calls is reduced.
Note: Declaring a friend function is a way to give private access to a non-member
function.

// C++ Program to demonstrate the

// functioning of a friend class

#include <iostream>

using namespace std;

class GFG {

24
private:

int private_variable;

protected:

int protected_variable;

public:

GFG()

private_variable = 10;

protected_variable = 99;

// friend class declaration

friend class F;

};

// Here, class F is declared as a

// friend inside class GFG. Therefore,

// F is a friend of class GFG. Class F

// can access the private members of

// class GFG.

class F {

public:

void display(GFG& t)

cout << "The value of Private Variable = "

25
<< t.private_variable << endl;

cout << "The value of Protected Variable = "

<< t.protected_variable;

};

// Driver code

int main()

GFG g;

F fri;

fri.display(g);

return 0;
}

Output
The value of Private Variable = 10
The value of Protected Variable = 99

Friend Function
Like a friend class, a friend function can be granted special access to private and
protected members of a class in C++. They are the non-member functions that can
access and manipulate the private and protected members of the class for they are
declared as friends.
A friend function can be:
1. A global function
2. A member function of another class

26
Friend Function in C++

Syntax:
friend return_type function_name (arguments); // for a global function
or
friend return_type class_name::function_name (arguments); // for a member function
of another class

Friend Function Syntax

1. Global Function as Friend Function

We can declare any global function as a friend function. The following example
demonstrates how to declare a global function as a friend function in C++:
Example:

// C++ program to create a global function as a friend

// function of some class

27
#include <iostream>

using namespace std;

class base {

private:

int private_variable;

protected:

int protected_variable;

public:

base()

private_variable = 10;

protected_variable = 99;

// friend function declaration

friend void friendFunction(base& obj);

};

// friend function definition

void friendFunction(base& obj)

cout << "Private Variable: " << obj.private_variable

<< endl;

28
cout << "Protected Variable: " << obj.protected_variable;

// driver code

int main()

base object1;

friendFunction(object1);

return 0;
}

Output
Private Variable: 10
Protected Variable: 99

2. Member Function of Another Class as Friend Function

We can also declare a member function of another class as a friend function in C++.
The following example demonstrates how to use a member function of another class as
a friend function in C++:
Example:

// C++ program to create a member function of another class

// as a friend function

#include <iostream>

using namespace std;

class base; // forward definition needed

// another class in which function is declared

class anotherClass {

public:

void memberFunction(base& obj);

29
};

// base class for which friend is declared

class base {

private:

int private_variable;

protected:

int protected_variable;

public:

base()

private_variable = 10;

protected_variable = 99;

// friend function declaration

friend void anotherClass::memberFunction(base&);

};

// friend function definition

void anotherClass::memberFunction(base& obj)

cout << "Private Variable: " << obj.private_variable

<< endl;

cout << "Protected Variable: " << obj.protected_variable;

30
}

// driver code

int main()

base object1;

anotherClass object2;

object2.memberFunction(object1);

return 0;
}

Output
Private Variable: 10
Protected Variable: 99

Constructors

Constructors are special class members which are called by the compiler every time an
object of that class is instantiated. Constructors have the same name as the class and
may be defined inside or outside the class definition. There are 3 types of constructors:
 Default Constructors
 Parameterized Constructors
 Copy Constructors

Default Constructor:
A default constructor is a constructor that doesn’t take any argument. It has no
parameters. It is also called a zero-argument constructor.

Syntax of Default Constructor


className() {
// body_of_constructor
}

Parameterized Constructor in C++


Parameterized Constructors make it possible to pass arguments to constructors.
Typically, these arguments help initialize an object when it is created. To create a
parameterized constructor, simply add parameters to it the way you would to any other
function. When you define the constructor’s body, use the parameters to initialize the
object.

Syntax of Parameterized Constructor


className (parameters...) {
// body
}

31
// C++ program to demonstrate constructors

#include <bits/stdc++.h>

using namespace std;

class Geeks

public:

int id;

//Default Constructor

Geeks()

cout << "Default Constructor called" << endl;

id=-1;

//Parameterized Constructor

Geeks(int x)

cout <<"Parameterized Constructor called "<< endl;

id=x;

};

int main() {

// obj1 will call Default Constructor

Geeks obj1;

32
cout <<"Geek id is: "<<obj1.id << endl;

// obj2 will call Parameterized Constructor

Geeks obj2(21);

cout <<"Geek id is: " <<obj2.id << endl;

return 0;
}

Output
Default Constructor called
Geek id is: -1
Parameterized Constructor called
Geek id is: 21

A Copy Constructor creates a new object, which is an exact copy of the existing
object. The compiler provides a default Copy Constructor to all the classes.
Syntax:
class-name (class-name &){}

Destructor
Destructor is an instance member function that is invoked automatically whenever an
object is going to be destroyed. Meaning, a destructor is the last function that is going
to be called before an object is destroyed.
 A destructor is also a special member function like a constructor. Destructor
destroys the class objects created by the constructor.
 Destructor has the same name as their class name preceded by a tilde (~)
symbol.
 It is not possible to define more than one destructor.
 The destructor is only one way to destroy the object created by the
constructor. Hence destructor can-not be overloaded.
 Destructor neither requires any argument nor returns any value.
 It is automatically called when an object goes out of scope.
 Destructor release memory space occupied by the objects created by the
constructor.
 In destructor, objects are destroyed in the reverse of an object creation.
The thing is to be noted here if the object is created by using new or the constructor
uses new to allocate memory that resides in the heap memory or the free store, the
destructor should use delete to free the memory.
Syntax
The syntax for defining the destructor within the class:
~ <class-name>() {
// some instructions
}
The syntax for defining the destructor outside the class:
<class-name> :: ~<class-name>() {

33
// some instructions
}
Example:-
// C++ program to demonstrate the execution of constructor
// and destructor

#include <iostream>
using namespace std;

class Test {
public:
// User-Defined Constructor
Test() { cout << "\n Constructor executed"; }

// User-Defined Destructor
~Test() { cout << "\nDestructor executed"; }
};
main()
{
Test t;

return 0;
}

Output
Constructor executed
Destructor executed

Inheritance:-
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.
When we say derived class inherits the base class, it means, the derived class inherits
all the properties of the base class, without changing the properties of base class and
may add new features to its own. These new features in the derived class will not affect
the base class. The derived class is the specialized class for 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.

Types Of Inheritance:-
1. Single inheritance
2. Multilevel inheritance
3. Multiple inheritance
4. Hierarchical inheritance
5. Hybrid inheritance

34
Types of Inheritance in C++

1. Single Inheritance: In single inheritance, a class is allowed to inherit from only one
class. i.e. one subclass is inherited by one base class only.

Syntax:
class subclass_name : access_mode base_class
{
// body of subclass
};
OR
class A
{
... .. ...
};
class B: public A
{
... .. ...
};

// C++ program to explain

// Single inheritance

#include<iostream>

using namespace std;

// base class

class Vehicle {

public:

Vehicle()

cout << "This is a Vehicle\n";

};

// sub class derived from a single base classes

class Car : public Vehicle {

35
};

// main function

int main()

// Creating object of sub class will

// invoke the constructor of base classes

Car obj;

return 0;

Output
This is a Vehicle

2. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can


inherit from more than one class. i.e one subclass is inherited from more than
one base class.

Syntax:
class subclass_name : access_mode base_class1, access_mode base_class2, ....
{
// body of subclass
};
class B
{
... .. ...
};
class C
{
... .. ...
};
class A: public B, public C
{
... ... ...
};

36
Here, the number of base classes will be separated by a comma (‘, ‘) and the access
mode for every base class must be specified.

// C++ program to explain


// multiple inheritance
#include <iostream>
using namespace std;

// first base class


class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};

// second base class


class FourWheeler {
public:
FourWheeler()
{
cout << "This is a 4 wheeler Vehicle\n";
}
};

// sub class derived from two base classes


class Car : public Vehicle, public FourWheeler {
};

// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base classes.
Car obj;
return 0;
}

Output
This is a Vehicle
This is a 4 wheeler Vehicle

3. Multilevel Inheritance: In this type of inheritance, a derived class is created from


another derived class.

37
Syntax:-
class C
{
... .. ...
};
class B:public C
{
... .. ...
};
class A: public B
{
... ... ...
};

// C++ program to implement


// Multilevel Inheritance
#include <iostream>
using namespace std;

// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};

// first sub_class derived from class vehicle


class fourWheeler : public Vehicle {
public:
fourWheeler()
{
cout << "Objects with 4 wheels are vehicles\n";
}
};
// sub class derived from the derived base class fourWheeler
class Car : public fourWheeler {
public:

38
Car() { cout << "Car has 4 Wheels\n"; }
};

// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base classes.
Car obj;
return 0;
}

Output
This is a Vehicle
Objects with 4 wheels are vehicles
Car has 4 Wheels

4. Hierarchical Inheritance: In this type of inheritance, more than one subclass is


inherited from a single base class. i.e. more than one derived class is created from a
single base class.

Syntax:-
class A
{
// body of the class A.
}
class B : public A
{
// body of class B.
}
class C : public A
{
// body of class C.
}
class D : public A
{
// body of class D.
}

// C++ program to implement

39
// Hierarchical Inheritance
#include <iostream>
using namespace std;

// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};

// first sub class


class Car : public Vehicle {
};

// second sub class


class Bus : public Vehicle {
};

// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base class.
Car obj1;
Bus obj2;
return 0;
}

Output
This is a Vehicle
This is a Vehicle

5. Hybrid (Virtual) Inheritance: Hybrid Inheritance is implemented by combining


more than one type of inheritance. For example: Combining Hierarchical inheritance
and Multiple Inheritance.
Below image shows the combination of hierarchical and multiple inheritances:

40
// C++ program for Hybrid Inheritance

#include <iostream>
using namespace std;

// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};

// base class
class Fare {
public:
Fare() { cout << "Fare of Vehicle\n"; }
};

// first sub class


class Car : public Vehicle {
};

// second sub class


class Bus : public Vehicle, public Fare {

41
};

// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base class.
Bus obj2;
return 0;
}

Output
This is a Vehicle
Fare of Vehicle

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. A
real-life example of polymorphism is a person who at the same time can have different
characteristics. A man at the same time is a father, a husband, and an employee. So
the same person exhibits different behavior in different situations. This is called
polymorphism. Polymorphism is considered one of the important features of Object-
Oriented Programming.

Types of Polymorphism
 Compile-time Polymorphism
 Runtime Polymorphism

42
Types of 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. In simple terms, it is a feature
of object-oriented programming providing many functions that have the same name
but distinct parameters when numerous tasks are listed under one function name.
There are certain Rules of Function Overloading that should be followed while
overloading a function.
Below is the C++ program to show function overloading or compile-time polymorphism:

// C++ program to demonstrate

// function overloading or

// Compile-time Polymorphism

#include <bits/stdc++.h>

using namespace std;

class Geeks {

public:

// Function with 1 int parameter

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

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

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

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.
Below is the C++ program to demonstrate operator overloading:

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

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

2. Runtime Polymorphism
This type of polymorphism is achieved by Function Overriding. Late binding and
dynamic polymorphism are other names for runtime polymorphism. The function call is
resolved at runtime in runtime polymorphism. In contrast, with compile time
polymorphism, the compiler determines which function call to bind to the object after
deducing it at runtime.

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.

46
Function overriding Explanation

Runtime Polymorphism with Data Members


Runtime Polymorphism cannot be achieved by data members in C++. Let’s see an
example where we are accessing the field by reference variable of parent class which
refers to the instance of the derived class.

// C++ program for function overriding with data members

#include <bits/stdc++.h>

using namespace std;

// base class declaration.

class Animal {

public:

string color = "Black";

};

// inheriting Animal class.

class Dog : public Animal {

47
public:

string color = "Grey";

};

// Driver code

int main(void)

Animal d = Dog(); // accessing the field by reference

// variable which refers to derived

cout << d.color;


}

Output
Black

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
Below is the C++ program to demonstrate virtual function:

// C++ Program to demonstrate

// the Virtual Function

#include <iostream>

using namespace std;

// Declaring a Base class

class GFG_Base {

public:

// virtual function

48
virtual void display()

cout << "Called virtual Base Class function"

<< "\n\n";

void print()

cout << "Called GFG_Base print function"

<< "\n\n";

};

// Declaring a Child Class

class GFG_Child : public GFG_Base {

pubic:

void display()

cout << "Called GFG_Child Display Function"

<< "\n\n";

void print()

cout << "Called GFG_Child print Function"

<< "\n\n";

};

49
// Driver code

int main()

// Create a reference of class GFG_Base

GFG_Base* base;

GFG_Child child;

base = &child;

// This will call the virtual function

base->GFG_Base::display();

// this will call the non-virtual function

base->print();
}

Output
Called virtual Base Class function

Called GFG_Base print function

Template
A template is a simple yet very powerful tool in C++. The simple idea is to pass the
data type as a parameter so that we don’t need to write the same code for different
data types. For example, a software company may need to sort() for different data
types. Rather than writing and maintaining multiple codes, we can write one sort() and
pass the datatype as a parameter.

50
C++ adds two new keywords to support templates: ‘template’ and ‘type name’. The
second keyword can always be replaced by the keyword ‘class’.

// C++ Program to demonstrate

// Use of template

#include <iostream>

using namespace std;

// One function works for all data types. This would work

// even for user defined types if operator '>' is overloaded

template <typename T> T myMax(T x, T y)

return (x > y) ? x : y;

int main()

// Call myMax for int

cout << myMax<int>(3, 7) << endl;

// call myMax for double

cout << myMax<double>(3.0, 7.0) << endl;

// call myMax for char

cout << myMax<char>('g', 'e') << endl;

return 0;

Output
7
7
g

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

51
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
}
#include <iostream>

using namespace std;

inline int cube(int s) { return s * s * s; }

int main()

cout << "The cube of 3 is: " << cube(3) << "\n";

return 0;

Output:- The cube of 3 is: 27

“this” pointer:-
To understand ‘this’ pointer, it is important to know how objects look at functions and
data members of a class.
1. Each object gets its own copy of the data member.
2. All-access the same function definition as present in the code segment.
Meaning each object gets its own copy of data members and all objects share a single
copy of member functions.

#include<iostream>

using namespace std;

/* local variable is same as a member's name */

class Test

private:

int x;

public:

void setX (int x)

52
// The 'this' pointer is used to retrieve the object's x

// hidden by the local variable 'x'

this->x = x;

void print() { cout << "x = " << x << endl; }

};

int main()

Test obj;

int x = 20;

obj.setX(x);

obj.print();

return 0;

Output:
x = 20

References
A. Book: OBJECT ORIENTED PROGRAMMING WITH C++
E. BALAGURUSAMY
Tata McGraw-Hill Publishing Company Limited
B. Website: GeeksforGeeks

53

You might also like