CPP Assignment
CPP Assignment
SUBJECT : PROGRAMMING IN
C++
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:
int main ()
cout<<"Hello World";
return 0;
// End of example
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.
3
Float 4 3.4E-38 to 3.4E+38
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,
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
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
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
#include <iostream>
int main()
int a = 8, b = 3;
// Addition operator
// Subtraction operator
// Multiplication operator
// Division operator
// Modulo operator
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:
#include <iostream>
int main()
int a = 6, b = 4;
// Equal to operator
9
// Lesser than operator
// true
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
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:
#include <iostream>
int main()
int a = 6, b = 4;
// Logical OR 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:
#include <iostream>
int main()
int a = 6, b = 4;
// Binary OR operator
13
// Left Shift operator
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:
#include <iostream>
int main()
int a = 6, b = 4;
15
// Assignment Operator
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)
16
Example:
#include <iostream>
int main()
int a = 3, b = 4;
// Conditional Operator
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
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)
1. left-to-
() Parentheses (function call)
right
18
Preced Oper Associ
ence ator Description ativity
right-to-
++/– Prefix increment/decrement
left
Logical negation/bitwise
!~
complement
* Dereference
left-to-
3. *,/,% Multiplication/division/modulus
right
left-to-
4. +/- Addition/subtraction
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
left-to-
15. , expression separator
right
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;
21
// C++ program to demonstrate accessing of data members
#include <bits/stdc++.h>
class Geeks {
// Access specifier
public:
// Data Members
string geekname;
// Member Functions()
};
int main()
Geeks obj1;
obj1.geekname = "Abhi";
obj1.printname();
return 0;
}
Output
Geekname is:Abhi
22
// declaration outside class
#include <bits/stdc++.h>
class Geeks
public:
string geekname;
int id;
void printname();
void printid()
};
void Geeks::printname()
int main() {
23
Geeks obj1;
obj1.geekname = "xyz";
obj1.id=15;
// call printname()
obj1.printname();
// 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.
#include <iostream>
class GFG {
24
private:
int private_variable;
protected:
int protected_variable;
public:
GFG()
private_variable = 10;
protected_variable = 99;
friend class F;
};
// class GFG.
class F {
public:
void display(GFG& t)
25
<< t.private_variable << endl;
<< 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
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:
27
#include <iostream>
class base {
private:
int private_variable;
protected:
int protected_variable;
public:
base()
private_variable = 10;
protected_variable = 99;
};
<< 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
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:
// as a friend function
#include <iostream>
class anotherClass {
public:
29
};
class base {
private:
int private_variable;
protected:
int protected_variable;
public:
base()
private_variable = 10;
protected_variable = 99;
};
<< endl;
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.
31
// C++ program to demonstrate constructors
#include <bits/stdc++.h>
class Geeks
public:
int id;
//Default Constructor
Geeks()
id=-1;
//Parameterized Constructor
Geeks(int x)
id=x;
};
int main() {
Geeks obj1;
32
cout <<"Geek id is: "<<obj1.id << endl;
Geeks obj2(21);
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
{
... .. ...
};
// Single inheritance
#include<iostream>
// base class
class Vehicle {
public:
Vehicle()
};
35
};
// main function
int main()
Car obj;
return 0;
Output
This is a Vehicle
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.
// 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
37
Syntax:-
class C
{
... .. ...
};
class B:public C
{
... .. ...
};
class A: public B
{
... ... ...
};
// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};
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
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.
}
39
// Hierarchical Inheritance
#include <iostream>
using namespace std;
// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};
// 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
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"; }
};
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:
// function overloading or
// Compile-time Polymorphism
#include <bits/stdc++.h>
class Geeks {
public:
43
void func(int x)
// 1 double parameter
void func(double x)
// 2 int parameters
cout << "value of x and y is " << x << ", " << y
<< endl;
};
// Driver code
int main()
Geeks obj1;
obj1.func(7);
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:
// Operator Overloading or
// Compile-Time Polymorphism
#include <iostream>
class Complex {
private:
public:
Complex(int r = 0, int i = 0)
real = r;
imag = i;
45
// when '+' is used with between
Complex res;
return res;
void print() { cout << real << " + i" << imag << endl; }
};
// Driver code
int main()
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
#include <bits/stdc++.h>
class Animal {
public:
};
47
public:
};
// Driver code
int main(void)
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:
#include <iostream>
class GFG_Base {
public:
// virtual function
48
virtual void display()
<< "\n\n";
void print()
<< "\n\n";
};
pubic:
void display()
<< "\n\n";
void print()
<< "\n\n";
};
49
// Driver code
int main()
GFG_Base* base;
GFG_Child child;
base = &child;
base->GFG_Base::display();
base->print();
}
Output
Called virtual Base Class 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’.
// Use of template
#include <iostream>
// One function works for all data types. This would work
return (x > y) ? x : y;
int main()
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>
int main()
cout << "The cube of 3 is: " << cube(3) << "\n";
return 0;
“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>
class Test
private:
int x;
public:
52
// The 'this' pointer is used to retrieve the object's x
this->x = x;
};
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